Docs

Everything You Need to Know

DOM

API

ChocolateChip-UI's DOM library has the following methods. Most of these are identical to those of the same name in jQuery.

$(selector)

This works the same as jQuery. You can provide any valid DOM/CSS selector. If there is a match for the selector, it returns the element. Otherwise it returns and empty DOM stack. Running DOM methods on an empty DOM stack will do nothing, erring silently.

var listItems = $('li');
var class = $('.items');
var id = $('#item');
var attr = $([type']);
var attr2 = $([type='text']);

$(function)

Like jQuery, this lets you run a function when the browser's DOM has loaded.

$(function() {
  // Do stuff when the DOM is ready.
});

You can have multiple functions in your document. They will be execute one after the other in order. If the DOM is already loaded, this function will execute immediately.

$(markup)

By passing in valid markup, this creates DOM nodes that can be inserted into the docuemnt.

var nodes = $('<p>This is a paragraph</p>');
var list = $('<ul><li>One</li><li>Two</li></ul>');

$.html(markup)

This works the same as the previous method. You pass it a string of valid markup and it returns DOM nodes which you can then insert into the document.

var nodes = $.html('<p>This is a paragraph</p>');
var list = $.html('<ul><li>One</li><li>Two</li></ul>');

element.find(selector) - find descendant

This method let you find a select that is a descendent of the element it is anchored to.

// Get the current screen:
var screen = $('screen.current');
// Find all lists in the current screen:
screen.find('.list');

element.is(selector)

This method lets you test the element against the provided selector. It returns a boolean true/false.

var list = $('.list');
if (list.is('ul')) {
  console.log('We got a list.');
}

element.not(selector)

This method eliminates elements from a collection that do not match the selector.

// Get uls that do not have the class `list`:
var unorderedList = $('ul').not('.list');

element.has(selector)

This method lets you get elements whose descedents match the selector.

// Get a list that is not empty;
var list = $('.list').has('li');

element.prev(selector?)

This method lets you get the element before the current. You can pass it a select to use. In that case the previous element must match the selector.

// Get the previous element:
var prev = $('ul').prev();

// Get previous element if it is an H2:
var prev = $('ul').prev('h2');

element.prevAll(selector?)

This method lests you get all the element before the current element. You can pass it a selector to match the previous elements against.

// Get all previous elements:
var prevEls = $('ul').prevAll();

// Get previous elements that are H2s:
var prevEls = $('ul').prevAll('h2');

element.next(selector?)

Get the next element after the element. You can pass it a selector to check against.

// Get the next element:
var next = $('ul').next();

// Get next element that is a p tag:
var next = $('ul').next('p');

element.nextAll(selector?)

Get all the next elements. You can pass this a selector to match against.

// Get all next elements:
var nextEls = $('ul').nextAll();

// Get all next elements that are p tags:
var nextEls = $('ul').nextAll('p');

element.first()

Get the first element out of a collection.

var firstItem = $('li').first();

element.last()

Get the last element of a collection.

var lastItem = $('li').last();

element.index(element?)

Get the position of an element in a collection. This is a zero-based number. If no argument is provided, it gets the position of the element this is executed on in relation to its siblings. If an element is passed as an argument, it checks to see what its position is in relation to the collection this is executed against.

// Get the index of a p tag:
var paragraphPos = $('p').index();

// Get the index of a select list item:
var selectedListItem = $('.selected');
var pos = $('li').index(selectedListItem);

element.children(selector?)

This method lets you get the children of an element. If you provide a select, the return children must match it.

// Get the list's children:
var listItems = $('ul').children();

// Get only li elements:
var listItems = $('ul').children('li');

element.siblings(selector?)

Get the siblings of an element. If a selector is provided, the sibings must match it.

// Get all siblings of `.selected`:
var siblings = $('.selected').siblings();

// Get siblings that are list items:
var siblings = $('.selected').siblings('li');

element.parent()

Get the parent of an element.

var parent = $('ul').parent();

element.closest(selector)

Get an element's ancestor that matches the provided selector.

var section = $('.list').closest('section');

element.css(property)

This method lets you get the value of a provided CSS property on the element.

// Get the following CSS properties:
var width = $('ul').css('width');
var color = $('h3').css('color');

element.css(property, value)

By passing this method two arguments, You can set the CSS properties of an element. CSS can be set in two ways: as two arguments - a property and a value - separated by a comma, or as a object of key value pairs.

// Set some CSS properties:
$('ul').css('color', 'red');
$('li').css('padding', '2px');

// Use an object to set the values:
$('ul').css({padding: '2px', color: 'red'});

element.width()

This method returns the width of an element. This value is the width plus any padding. It does not include margins or border widths. The value returned is a number without any length identifier.

var width = $('screen.current').width();

element.height()

This method returns the height of an element. This value is the height plus any padding. It does not include margins or border widths. The value returned is a number without any length identifer.

var height = $('ul').height();

element.before(content)

This method allows you to insert content before an element. The argument should be valid markup.

$('ul').before('<h2>The Title</h2>');

element.after(content)

This method lets you insert content after an element. This argument should be valid markup.

$('ul').after('<summary>This is the list summary.</summary>');

element.prepend(content)

This method allows you to prepend content to an element. That means the content is inserted at the beging of the elements children.

$('ul').prepend('<li><h3>A new item</h3></li>');

element.append(content)

This method allows you to append content to an element. That means the content is inserted as the last children of the element.

$('ul').append('<li><h3>A new, last item</h3></li>');

element.prependTo(selector)

This method allows you to take some content and prepend it to an element. The order of how this happens is a little different from prepend().

var ul = $('ul');
$('<li><h3>A new item</h3></li>').prependTo(ul);

// Or you could pass a DOM node:
$('li.selected').prependTo('ul');

element.appendTo(selector)

This method allows you to append content to a selector. The order of how this happends is a little different from append().

var ul = $('ul');
$('<li><h3>A new item</h3></li>').appendTo(ul);

// Or you could pass a DOM node:
$('li.selected').appendTo('ul');

element.clone(true?)

This element allows you to clone an element. If a boolean true argument is provided, deep clone is performed.

var clone = $('ul.list').clone();

// Perform a deep clone:
var clone = $('ul.list').clone(true);

element.wrap(markup)

Wrap an element in the provided markup. When doing this, any events that were attached to the elements being wrap with be disconnect. You'll want to remove the events first to prevent memory leaks, then wrap them, then re-apply the events.

var list = $('ul');
list.wrap('<div class="list-wrapper"></div>');

element.unwrap()

This method will unwrap a element from its immediate parent. If the elements being unwrapped have bound events, this will break. Therefore you should unbind events from any elements you intend to unwrap. You can re-bind the events after unwrapping.

$('ul').unwrap();

element.offset()

Retrieve the current position of an element relative to the document. This method returns an object with the left and top positions.

var offset = $('ul').offset();
// offset = {left: 200, top: 60}

element.position()

This method returns the position of an element relative to its parent. Contrast that with offset above.

var position = $('li.selected').position();
// positon = {left: 10, top 100}

element.empty()

This method deletes all the child elements of the element it is executed on.

// Delete a list's content:
$('ul').empty()

element.html(content)

This method allows you to set the content of an element. The content should be valid markup.

$('.list').html('<li><h3>A new item</h3></li>')

Note about element.html(content)

ChocolateChip-UI's implementation differs from jQuery in that to create HTML elements, the markup must be valid HTML5. jQuery allows using its own shorthand markup, such as <div/> or <ul/>. Since this is not valid HTML5 markup, it will fail in ChocolateChip-UI. You need to use <div></div> or <ul></ul>.

element.html()

This method lets you get the content of an element.

var listContent = $('ul').html();

element.text(content)

This method lets you set the text content of an element.

$('h2').text('This is the title');

element.text()

This method lets you get the text of an element.

var title = $('h2').text();

element.remove()

This method removes the element it is executed on. Before removing the element, all events are unbound.

$('li.selected').remove();

element.replaceWith(content)

This method replaces the element it is executed on with the provided content, which may be markup for new elements or a node of a currently existing element in the document.. Before removing the element, all events are unbound from it and, if the element that will replace it is already in the DOM, from the replacement element as well.

// Replace element with new content:
$('li.selected').replaceWith('<li><h3>New content!</h3></li>');

// Replace one element with another:
$('li.selected').replaceWith($('li:first-of-type'));

element.addClass(className)

This method lets you add a class to an element.

$('li').addClass('special');

element.hasClass(className)

This method lets you test if an element has the provided class. It returns a boolean true/false.

if ('li').hasClass('selected')) {
  console.log('found a selected one.')
}

element.removeClass(className)

This method removes the provided class from an element.

$('screen').removeClass('current');

element.toggleClass(className)

This method allows you to toggle a class on an element. If the class is not present the first time it run, then it adds it, otherwise it removes it.

$('li').on('tap', function() {
  $(this).toggleClass('selected');
});

element.attr(property)

Get the value of the provided property on an element.

var ariaVisible = $('li.selected').attr('aria-hidden');

element.attr(property, value)

This method allows you to set the value of a property on an element.

$('li').attr('aria-hidden', true);

element.removeAttr(property)

This method lets you remove an attribute from an element.

$('li').removeAttr('aria-hidden');

element.prop(property)

This method lets you get a property of an element.

var disabled = $('input').prop('disabled');

element.prop(property, value)

This method lets you set a property on an element.

$('input').prop('disabled', true);

element.removeProp(property)

This method lets you remove a property from an element.

$('input').removeProp('disabled');

element.disable().

This method lets you disable a form element.

$('button').disable();

element.enable()

This method lets you enable a form element.

$('button').enable();

element.val(value)

This method lets you set the value of a form element.

$('#nameInput').val('John Doe');

element.val()

This method lets you get the value of a form element.

var name = $('#nameInput').val();

element.hide()

This method lets you hide an element.

$('li').is('.selected').hide();

element.show()

This method lets you show a hidden element.

$('li').show();

element.data(key, value)

This method lets you store a key value pair on an element.

$('ul').data('price-list', [5,12,4,6,11,5.5]);

element.data(key)

This method lets you get the data store on an element using its key.

var prices = $('ul').data('price-list');

element.removeData(key)

This method lets you remove a store item from a list.

$('ul').removeData('price-list');

element.on(event, callback, type)

This method lets you bind an event to an element.

$('button').on('tap', function() {
  alert('You just tapped!');
}, false);

element.on(event, element, callback, type)

This method allows you to register a delegated event on a element. You use delegated event when you need to register events on multiple items, such as list items.

$('ul').on('tap', 'li', function() {
  alert($('this').text());
});

element.off(event, callback, type)

This method lets you remove an event from an element. If no arguments are provided, all events will be removed.

// Remove tap event:
$('button').off('tap');

// Remove all events from list:
$('ul').off();

element.off(event, element, callback, type)

This method lets you remove delegated events.

// Remove delegated events from list items:
$('ul').off('tap', 'li');

element.trigger(event, data?)

This method lets you trigger the provided event on the element.

$('button').trigger('tap');

Optionally, you can pass a data object with the tirggered event. This gets passed to the callback on the event as the data property. You can access this from the callback's event:

// Setup event listener:
$('#button').on('tap', function(e) {
  if (e.data) {
    alert(e.data.msg);
  } else {
    alert('Nothing to say for now.')
  }
});

// Trigger event and pass data:
$('#button').trigger('tap', { msg: 'This is from the trigger. Hello!'});

element.serializeArray()

This method create an array of key-value objects from a form's elements.

var data = $(form).serializeArray();

element.serialize()

This method creates a text string in standard URL-encoded notation.

var data = $(form).serialize();

$.param(obj, traditional)

This method lets you create a serialized representation of an array or a plain object suitable for use in a URL query string or a Fetch request.

var myObject = {
  a: {
    one: 1,
    two: 2,
    three: 3
  },
  b: [ 1, 2, 3 ]
};
var recursiveEncoded = $.param(myObject);

element.eq(index)

Get an element based on its position in a collection. This uses zero-based numbers.

$('li').eq(4).addClass('important');

element.push(element)

Push an element onto the collection.

var listItem = $('#firstList').find('li').eq(2);
$('#list').find('li').push(listItem);

element.pop()

This method lets you pop the last item off of a collection.

var listItems = $('li');
listItems.pop();

element.unshift(element)

This method lets you add an element to the start of a collection.

var listItem = $('#firstList').find('li').eq(2);
$('#list').find('li').unshift(listItem);

element.shift()

This method lets you remove an element from a collection.

$('li').shift();

element.forEach(callback)

This method lets you execute a callback on each item in the collection. Its arguments follow the normal JavaScript convention of context followed by index.

$('li').each(function(item) {
    $('item').append(' Sold!');
});

element.each(callback)

This method lets you execute a callback on each item in the collection. Its arguments follow the jQuery convention of index and context.

$('li').each(function(item) {
    $('item').append(' Sold!');
});

element.slice()

This method works just like the array equivalent.

element.splice()

This method works just like the array equivalent.

element.filter(callback)

This method works just like the array equivalent.

element.map(callback)

This method works just like the array equivalent.

element.every(callback)

This method works just like the array equivalent.

element.some(callback)

This method works just like the array equivalent.

element.unique()

This method removes any duplicate elements in the collection.

var listItems = $('li').unique();

element.get()

This method returns an array of DOM nodes from the DOMStack. The DOMStack is a special object abstraction that has the above special methods to interact with the DOM nodes it contains. This method lets you get just the nodes themselves as a simple JavaScript array.

// Get the list items:
var li = $('li');
// Get the DOM nodes:
var nodes = li.get();

element.length

This is not a method, but a property on a DOMStack. It indicates the number of nodes a DOMStack contains. It does not you use methods to add or remove items from the DOMStack, this value will be updated. However, because a DOMStack is an object, you cannot change it to change the number of items in the DOMStack. Do not attempt to change this value!. Use push, pop, and other DOMStack methods to change the number of items.

// Find out how many list items:
var li = $('li');
console.log(li.length);

element[0]

Sometimes you need to get at the plain DOM node. This might be because you want to drop down to plain JavaScript while accessing the properties of a DOM element. To get at the node itself, you can access it direclty using [0] on the node. This only works for the first element. If you want to get at the node at a later position in a collection, use the element.eq() with this:

// Get the first list item:
if ($('li')[0].nodeName === 'LI') {
  alert('Got a list item!');
}
// Get the third list item/
// Remember that `eq` is zero-based:
var li3 = $('li').eq(2)[0];
console.log(li3.nodeName);

$.replace(oldElement, newelement)

This method allows you to replace one element with another. The first argument is the element to replace, and the second argument is the element that will be replace it.

var list1 = $('#list1');
var list2 = $('#list2');
// Replace list1 with list2:
$.replace(list1, list2);

jQuery has replaceWith(), but it works quite differently from this. We feel ChocolateChip-UI's replace is more straightforward about what it's doing than jQuery's replaceWith. ChocolateChip-UI's replace works even when jQuery is present because it is included as a utlity plugin.

ChocolateChip-UI Exclusive

In order to make certain common tasks easier, ChocolateChip-UI has a number of DOM utility methods that reduce boilerplate code into one-liners. They are:

  • $(selector).iz(argument)
  • $(selector).iznt(argument)
  • $(selector).haz(argument)
  • $(selector).haznt(argument)
  • $(selector).hazClass(class)
  • $(selector).hazntClass(class)
  • $(selector).hazAttr(attribute)
  • $(selector).hazntAttr(attribute)
  • $(selector).disable()
  • $(selector).enable()
  • $(selector).forEach()

In normal JavaScript, when you perform a test, such as jQuery's $(selector).is(), $(selector).hasClass or plain JavaScript element.hasAttribute, these return a boolean value if there is a match or not. In contrast, ChocolateChip-UI's haz family of methods directly return the element if there is a match. This enbales you to write code as follows:

// Test if it is a link:
$('.menu').is('a').css('text-decoration', 'none');
// Test if button is disabled, then enable:
$('button').is('[disabled]').enable();
// Test if title is not an H1:
$('.title').isnt('h1').css({font-size: '14px'});
// Test if list has content:
$('ul').haz('li').addClass('list');
// Test if list is empty:
$('ul').haznt('li').html('<li>No content yet.</li>');
$('div').hazClass('important').prepend('<h5>Important<h5>')
$('input').hazAttr('disabled').hide();
$('button').disable();

iz(argument) & iznt(argument)

$(selector).iz(argument) returns the element when there is a match. $(selector).iznt returns the element when there isn't a match. These two can accept a number of different arguments, such as a node, a node name, a class or an attribute. When using string arguments, they should be valid CSS selectors, so ids require a '#', classes a '.' and attributes must be enclosed in brackets:

$(selector).iz(selector);
$(selector).iz('div').css('border', 'solid 1px green');
$(selector).iz('#main').addClass('super-important');
$(selector).iz('.selected').removeClass('selected');
$(selector).iz('[checked]').find('form').prepend('<h2>Order Now!</h2>');

// No match:
$(selector).iznt(selector);
$(selector).iznt('div').replace('<div>This is a DIV</div>');
$(selector).iznt('#main');
$(selector).iznt('.selected').addClass('selected');
$(selector).iznt('[checked]');

haz(argument) & haznt(argument)

$(selector).haz(argument) returns the element when it has the descendent element provided. $(selector).haznt(argument) returns the element when it does not have the descendent element provided. Because this checks for descendent elements, the argument must be a valid CSS selector.

// Selector has descendentas that are "li":
$(selector).haz('li');
// Selector has descendent with this class:
$(selector).haz('.special');
// Selector has descendent that is checked:
$(selector).haz('[checked]');

hazClass(class) & hazntClass(class)

$(selector).hazClass(class) returns the element when it has the class provided. $(selector).hazntClass(class) returns the element when it does not have the class provided.

// Get element if it has this class:
$(selector).hazClass('selected').prepend('<h4>READ THIS!<>');
// If it doesn't have the class:
$(selector).hazntClass('selected').remove('h4');

hazAttr(attributeName) & hazntAttr(attributeName)

$(selector).hazAttr(attributeName) returns the element when it has the attribute provided. $(selector).hazntAttr(attributeName) returns the element when it does not have the attribute provided. The argument is the name of the attribute you are testing for:

// Test for attribute:
$(selector).hazAttr('checked').addClass('selected');
$(selector).hazntAttr('checked').removeClass('selected');

disable() & enable()

$(selector).disable() allows you to disable a form element and adds the class 'disabled'. $(selector).enable() enables the form element and removes the class 'disabled'.

$(selector).forEach(ctx, idx)

This method lets you iterate over a collection of elements using normal JavaScript parameter order. jQuery also uses the index first, followed by the context. The normal parameter order for JavaScript is context first, followed by index. If you just want to get the context of the loop, then forEach is more convenient.

// Looping with each:
$('li').each(function(idx, ctx) {
  ctx.append('Woohoo!')
});
// Looping with forEach.
// No need for index parameter:
$('li').forEach(function(ctx) {
  ctx.append('Woohoo!')
});