Using the classList API

by kirupa   |   5 September 2013

Using JavaScript, a common way to style elements is by adding and removing class values. Traditionally, this way involved parsing an element's className property, separating all of the elements into an array, making your class value changes, and serializing the array back into a string. This is the approach web developers and popular JS libraries have been using for centuries, but this approach isn't particularly fun. If you aren't careful, it is also easy to make mistakes.

To help alleviate some of the inconvenience, we now have a new (and very performant) API that makes adding and removing class values from an element ridiculously easy. This new API is affectionately known as classList, and in this article, you will learn all about it.

Onwards!

Say Hello to classList

Using the classList API is pretty simple. Let's say we have the following div element:

<div id="myDiv" class="bar foo zorb"> ... </div>

From looking at the markup, we can see that this element has a class attribute with the bar, foo, and zorb values set. If you want to access these class values using the classList API, simply call it on the DOM element whose class values you want to inspect or modify.

Below is an example of the classList API at work:

var divElement = document.querySelector("#myDiv");
var classValues = divElement.classList;

alert(classValues);

If we ran this script, you would see a dialog that looks as follows:

bar foo zorb

Yay! Isn't this like the most exciting thing ever?

Right now, especially if you've used the className approach for working with class values before, you are probably not impressed. That is because what you are seeing is your classList API at its most modest self. Once you get to know it better, you'll realize that the classList API provides a handful of methods that will impress you a whole lot.

Those methods are:

  1. add
  2. remove
  3. toggle
  4. contains

What these four methods do may be pretty self-explanatory from their names, but let's look at them in further detail.

Adding Class Values

To add a class value to an element, call the add method on classList:

var divElement = document.querySelector("#myDiv");
divElement.classList.add("baz");

alert(divElement.classList);

After this code runs, our div element will have the following class values: bar, foo, zorb, baz. The classList API takes care of ensuring spaces are added between class values. If you inspect the value of our div element and examine its class attribute, things will look as you expect:

the baz value - it exists!

If you specify an invalid class value, the classList API will throw an exception and not add it. If you tell the add method to add a class that already exists on the element, your code will run without exception (ha!) but the duplicate class value will not get added.

Removing Class Values

To remove a class value, just call the remove method on classList:

var divElement = document.querySelector("#myDiv");
divElement.classList.remove("foo");

alert(divElement.classList);

After this code executes, the foo class value will be removed. What you will be left with is just bar and zorb. Pretty simple, right?

Toggling Class Values

For many styling scenarios, there is one very common workflow. First, you check if a class value on an element exists. If the value exists, you remove it from the element. If the value does not exist, you add that class value to the element. To simplify this very common toggling pattern, the classList API provides you with the toggle method:

var divElement = document.querySelector("#myDiv");
divElement.classList.toggle("foo"); // remove foo
divElement.classList.toggle("foo"); // add foo
divElement.classList.toggle("foo"); // remove foo

alert(divElement.classList);

The toggle method, as its name implies, adds or removes the specified class value on the element each time it is called. In our case, the foo class is removed the first time the toggle method is called. The second time, the foo class is added. The third time, the foo class is removed. You get the picture.

Checking if a Class Value Exists

The last thing we are going to look at is the contains method:

var divElement = document.querySelector("#myDiv");

if (divElement.classList.contains("bar") == true) {
	// do something
}

This method checks to see if the specified class value exists on the element. If the value exists, you get true. If the value doesn't exist, you get false.

Going Further

As you can see, the classList API provides you with almost everything you need to add, remove, or inspect class values on an element very easily. The emphasis being on the word almost. In the following sections, I provide snippets for some common cases I run into that go beyond what the classList API provides by default.

Clearing All Class Values

Sometimes, instead of removing a class value individually, you want to just get rid of all of them. The easiest way to do that is by setting the className property on an element to an empty string:

var divElement = document.querySelector("#myDiv");
divElement.className = "";

alert(divElement.classList.length); // returns 0

As an aside, take a look at the last line:

var divElement = document.querySelector("#myDiv");
divElement.className = "";

alert(divElement.classList.length); // returns 0

From the last line, notice that I can check the length property on classList to get a count of all the class values that currently exist on the element. This is possible because your classList is actually a DOMTokenList which provides all of the helpful methods you saw above in addition to the length properties and more. You can see more about the DOMTokenList in the W3C Spec for it.

Adding Multiple Class Values

If you ever have the itch to add multiple class values, don't scratch it by calling the built-in add method over and over again. Instead, use the following snippet for addmany:

DOMTokenList.prototype.addmany = function(input) {
	var classValues = input.split(' ');
	var classValuesCount = classValues.length;
	
	for (var i = 0; i < classValuesCount; i++) {
		this.add(classValues[i]);
	}
}

Use the addmany method on your classList to specify all the classes you wish to add separated by a space:

var divElement = document.querySelector("#myDiv");
divElement.classList.addmany("mario luigi toad");

alert(divElement.classList);

The end result is that the addmany method will take each class value you specify and add it to list of classes on the element. Because the addmany method uses the built-in add method internally, you get the error and duplicate checking for free.

Removing Multiple Class Values

If you want to remove multiple class values from your element, use the removemany snippet:

DOMTokenList.prototype.removemany = function(input) {
	var classValues = input.split(' ');
	var classValuesCount = classValues.length;
	
	for (var i = 0; i < classValuesCount; i++) { 
		if (this.contains(classValues[i])) {
			this.remove(classValues[i]);
		}
	}
}

Just call removemany from your classList and pass in the list of class values (separated by a space) you wish to remove:

var divElement = document.querySelector("#myDiv");
divElement.classList.removemany("foo zorb");

alert(divElement.classList);

The end result is that the class values you specify, if they exist on the element, will get removed. In our example, the foo and zorb class values will get removed. All that is going to be left on our div element is the bar class value.

Conclusion

The classList API is a small but very helpful addition to the giant bag of improvements that is HTML5. Remember, this API isn't just providing some convenience methods that save you time from writing a few lines of code. Because all of the functionality for adding, removing, toggling, and checking if a class value exists is built-in and provided by the browser, you get much faster performance than you would get by reimplementing this functionality yourself. The following Performance section puts some numbers behind my words.

With all of that said, this API is recent enough where it isn't supported by all browsers just yet. According to caniuse, the classList API is supported on over 75% of all browsers. If you care about older browsers and wish to introduce them to the joys that is classList, you can use the following shim.

Credits

The idea for this tutorial came from senocular who reminded me of classList's existence in his awesome simplification of my Filtering Items example.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!