LearnHow to Manipulate Classes Using the JavaScript classList API

Matt West
writes on February 8, 2023

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’ll learn how to manage classes using the classList API, part of the native JavaScript implementation in modern web browsers.

What Is the JavaScript classList API?

The JavaScript classList API enables us to manage classes using a variety of methods. For example, we can choose to add classes or determine if a class exists using the classList contains method.

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 JavaScript classList Object

Every HTML element has an object called classList that contains a list of the classes applied to the element and 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, including:

  • 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');

See If a Class Exists Using the classList Contains Method

You can check to see if a certain class is applied to an element using the classList 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 the classList contains 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.
}

Find 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);
}

BONUS: Finding Elements By Class

While 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 this 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

Learn More About JavaScript With Treehouse

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.

To learn even more about JavaScript, try our Techdegrees or courses for in-depth coding training, hands-on projects, and more. Sign up for a free trial today!

Further Reading

5 Responses to “How to Manipulate Classes Using the JavaScript classList API”

  1. Matt,

    It would be nice to have had the pros and cons of using this in website development. I have seen some testing and it appears that adding ‘classList’ to an element speeds up page load times. I would like to fine an explanation as to why?

  2. 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…??

  3. Matt , thank you for interesting article! I am just learning JS and this article was very userful for me.

Leave a Reply

You must be logged in to post a comment.

Want to learn more about Javascript?

Learn how to use JavaScript to add interactivity to websites.

Learn more