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.


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


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

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


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



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



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


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, 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 *