HTML5 classList API

html5 classList

DOM element class attributes are not only used as ‘hooks’ in CSS to create selectors by which developers and designers style pages, they are widely used in JavaScript for DOM programming. They are an integral part of front-end web development, and used by developers on a daily basis.

Hitherto, working with classes natively has been arduous. This has contributed to the rise in popularity of libraries that provide helper methods. jQuery for example, provides addClass(), hasClass(), removeClass(), and toggleClass(). These methods make working with classes a breeze. Surely, these methods should be available natively. Well, guess what? In addition to an array of new JavaScript APIs, HTML5 replenishes native JavaScript with classList.

The classList object provides the add, remove, contains and toggle methods to facilitate easy and quick class manipulation natively by developers. Let’s explore.

elem.classList

The classList object has the following properties:
{
   length: number, // returns a class count
   item: function(){ }, // index
   contains: function() { },
   add: function(){ },
   remove: function(){ }
}

elem.classList.contains(class)

The contains() method is used to check whether a class exists on the node or not. It returns a boolean value; true or false.

usage:
var myElem = document.querySelector(‘#wrapper’);
myElem.classList.contains(‘parent’);// returns true or false

elem.classList.add(class)

The add() method, as you might have gathered, adds a class to the selected node.

usage:
myElem.classList.add(‘new-class’);

elem.classList.remove(class)

Conversely, the remove() method removes the ‘passed’ class from the selected element.

usage:
myElem.classList.remove(‘new-class’);

elem.classList.toggle(class)

Yes, you guessed it, the toggle() method adds and removes the class. So, if the class exists, it is removed, and vice versa.

usage:
myElem.classList.toggle(‘my-class’);

This is predominately used with events such as click and hover.

Browser support

classList is well supported in modern browsers and as of this writing, according to canisue.com, global browser support stands at 75.6%. If you are supporting legacy IE, be sure to use a fall back for IE9 and below.

Useful resources

Leave a Reply

Your email address will not be published. Required fields are marked *