Notes on the classList API

For me the classList API is one of the most useful parts of HTML5. Manipulating classes is an everyday part of JavaScript on the web, but is a cowpath that required a sure foot to tread before before getting the full treatment from the pavers in the form of classList.

The basic syntax is element.classList.method where method can be one of the following:

var box = document.getElementById('box');
The class is now added in the DOM and declarations in CSS for .highlight will be applied to the element.

More classes can be added the same way, so you can go ahead with box.classList.add(‘highlight–sidebar’) or box.classList.add(‘l-wide’) or any other classes you like.

You can only add one class at a time, so box.classList.add(‘class-1’,‘class-2’) doesn’t work.

The class has been removed in the DOM and any side effects of that will be applied.

If there’s a button in our markup we can listen for clicks on it and use it to switch the highlight class on and off.

button = document.querySelector('button');
toggleBox = function() { box.classList.toggle('highlight'); };

It could be used to check if an image in a gallery has the class that makes it bigger than the rest or to check if a div has the class that makes it visually hidden for example.

if(box.classList.contains('highlight') {
    // do something
} else {
    // do something else

box.classList.item(0) === 'highlight';
box.classList.item(1) === 'highlight--sidebar';
box.classlist.item(2) === 'l-wide';
The number passed represents the position of the class name in the list, starting to count from 0.

Again it’s dead simple, although I have caught myself using square brackets as if it’s a normal array.

In the example above console.log(box.classList.length) returns 3 as we currently have 3 class names on the element, highlight, highlight–sidebar and l-wide.

Browser support is good and there are a couple of excellent polyfills I know of if you need to support older browsers. Bear in mind that JavaScript should be an enhancement in web pages so you should have a fallback in HTML and CSS that suffices for older browsers. Ask yourself do you need a polyfill before doing a copy/paste.