Manipulating Classes Using The classList API

Something that comes up often when building front-end web applications is the need to change the classes applied to an element. For some time elements have had a className attribute which allows you to retrieve a string containing the class names separated by spaces. This is useful, but it doesn’t provide a simple way of managing the classes on an element.

Many JavaScript libraries have implemented their own helper methods for managing classes. For example, jQuery has addClass(), removeClass(), hasClass(), and toggleClass() methods.

In this post you’re going to learn how to manage classes using the classList API. This is part of the native JavaScript implementation in modern web browsers. The main advantage of using this native API is that it doesn’t require that you include a library like jQuery in your project.

The classList Object

Every HTML element has an object called classList that contains a list of the classes applied to the element, as well as methods for managing those classes.

myEle.classList;

First and foremost, classList is a DOMTokenList which contains the classes applied to an element and a property called length that represents the total number of classes.

{
    0: "column-half",
    1: "wiki-column",
    2: "text-content",
    length: 3
}

The classList object also has five methods that can be used for managing classes. These are:

  • add (class)
  • contains (class)
  • item (index)
  • remove (class)
  • toggle (class)

Each of these methods should be called directly on the classList object.

Lets take a look at each of these methods in a little more detail.

Adding Classes

The add() method is used to apply a new class to an element.

myEle.classList.add('treehouse');

To avoid duplication, the class will only be added if it doesn’t already exist.

Removing Classes

The remove() method is used to drop a class from an element.

myEle.classList.remove('treehouse');

Toggle Classes

The toggle() method will add a class to an element if it’s not already present, or remove the class if it is.

myEle.classList.toggle('treehouse');

Checking if a Class Exists

You can check to see if a certain class is applied to an element using the contains() method. This method will return true if the specified class is present, and false if it’s not.

var present = myEle.classList.contains('treehouse');

You could use this method as the condition for an if/else statement, as shown in the example below.

if (myEle.classList.contains('treehouse')) {
    // Class exists!
} else {
    // Class not found.
}

Finding a Class by its Index in classList

The item() method is used to retrieve a class name using the index of the class in the classList. If nothing exists at the specified index the method will return null.

var index = myEle.classList.item(0);

This method can come in handy if you need to loop through each of the classes applied to an element.

for (var i = 0; i < myEle.classList.length; i++) {
    var class = myEle.classList.item(i);
}

Browser Support

Browser support for the classList API is good. Keep in mind that this feature was only added to Internet Explorer in version 10, so you may need to use an alternative if you need to support older versions of IE.

IE Firefox Chrome Safari Opera
10.0+ 3.6+ 8.0+ 5.1+ 11.5+

Support on mobile browsers is also very good.

iOS Safari Android Browser Opera Mobile Chrome for Android IE Mobile
5.0+ 3.0+ 11.1+ 31 10

Source: http://caniuse.com/#feat=classlist

BONUS: Finding Elements By Class

Whilst we’re on the topic of classes, lets take a look at a couple of methods that can be used to find elements using class names.

getElementsByClassName

The getElementsByClassName method will return a list of elements that have the specified class.

var elements = document.getElementsByClassName('treehouse');

You can also specify multiple class names by separating them with a space. In which case, all of the classes will need to be present on an element for it to be returned.

var elements = document.getElementsByClassName('treehouse mike frog');

Browser support for getElementsByClassName

querySelectorAll

The querySelectorAll method uses CSS selector syntax to find elements. You can match classes by preceding the class name with a dot, and IDs by using a pound-sign (#). Elements can be matched by just using the name of the tag.

var classEle = document.querySelectorAll('.treehouse');
var idEle = document.querySelectorAll('#treehouse');
var tagEle = document.querySelectorAll('div');

You can combine multiple selectors to create more complex queries just as you would in CSS.

var element = document.querySelectorAll('#main.treehouse');

The querySelectorAll method will return a list of all the elements that match your query. If you just wish to return a single element you can use the querySelector method. This will return the first element that matches the query.

Browser support for querySelectorAll

Summary

In this post you’ve learned how to use native JavaScript methods to manage the classes applied to HTML elements. A big advantage to using these methods over those provided by a JavaScript library like jQuery is that you don’t have the additional overhead of having to load an external library.

We’re starting to see more and more of the best features from jQuery (and other libraries) find their way into web browsers. Many of these libraries were initially developed to patch-up the basic JavaScript implementations in older browsers, so it’s nice to see this process coming full-circle.

Further Reading

Free Workshops

Watch one of our expert, full-length teaching videos. Choose from HTML, CSS or WordPress.

Start Learning

Comments

3 comments on “Manipulating Classes Using The classList API

  1. Thanks a lot Matt ,Your article helped me in understanding java script very easily ,because the way you written is very easy to understand .I am feeling fortunate to being here ,i like your website also..
    i have a question can you tell me something about google plus authorship…??