Manage HTML Classes with classList in JavaScript

Posted on Updated on JavaScript by Adam Laki

In case of a web page or an application, it is pretty common to add, remove, toggle classes on different elements to switch states. Using the classList object, we can do this with ease only with JavaScript.

The DOM manipulation was hard – like the element selection – only with JavaScript, but with appearance of jQuery, we had natural methods and patterns. Now, using the classList object, we can handle the class modifications on our elements.

Today this is a widely supported method in almost all of the browsers. It is a property on a DOM element and is read-only. A handy alternative to the className property.

The Syntax of the classList Object

The syntax is plain simple: we need an HTML element selected with JS and use one of the methods of the classList object.

We have six methods: add(), remove(), item(), toggle(), contains(), replace(). The names speak for themselves.

We can also access to the number of the classes with the object’s length property.

// Our HTML markup:
<div class="main is-front-page"></div>
// Our JS code:
let main = document.querySelector('.main');

// Our HTML result:
<div class="main is-sub-page"></div>

To see the complete object, you can run and log the element.classList. Here you can see the numbered classes (in an accessible array format), the length and on the prototype chain the methods.

Example classList object in Chrome Developer Tools

Add Class(es)

If you want to add a class to a selected or created item, apply the class names as parameters to the add() method.

// Add a new class to the ".main" element
// You can also add multiple classes separated with comma
main.classList.add('has-sidebar', 'is-dark-style');
// Our HTML result:
<div class="main is-sub-page has-sidebar is-dark-style"></div>

The good thing with these functions is that they don’t throw an error if something not right. What I mean is that if you add an existent class to an element, it won’t be added again. If you want to remove a non-existent attribute value, you neither get an error. It handles all of these quirks.

Remove Class(es)

To remove a specified class, we have to use the remove() method with the chosen name(s). Here we can also remove more than one item.

// Remove has-sidebar class from element main
// Our HTML result:
<div class="main is-sub-page is-dark-style"></div>

Note that here we can also use the spread syntax:

let classes = ['is-sub-page', 'is-dark-style'];
main.classList.remove(...classes );

Toggle Class

The toggling method is a useful one because we don’t have to write any statement. If an element contains the chosen class it will remove it; if a component doesn’t include the named class, it will add it (we don’t need an if statement with the contains method).

This function serves as a shortcut in our code in a lot of cases because we don’t have to choose between adding or removing.

// Toggle the selected class
// Our HTML result:
<div class="main has-sidebar"></div>

The function returns true if it adds the class and false if it removes it.

The toggle method has a second parameter which can control the two operations (adding, removing). If this second parameter is valid, it will add the class, if it evaluates to false it will remove it.

// Add/remove is-dark-style class, depending on colorScheme == 'dark' condition
main.classList.toggle('is-dark-style', colorScheme == 'dark' );

Replace Class

Using the classList.replace() method we can replace an existing class with another; this is handy¬† because it is a frequent pattern and we don’t have to use the remove() method before the add().

// Replace 'main' class with 'secondary'
div.classList.replace('main', 'secondary');
// Our HTML result:
<div class="secondary has-sidebar"></div>

Check If Element Contains Class

Checks if the named class exists on the selected element. We can use it’s return value in our if statements.

// Returns true

Get the Nth Class of an Element

Using the classList object’s item() method, we can get a class value by index.

// Returns 'has-sidebar'

Looking for web dev job?
You can check them on Jooble.

Need a web developer? Maybe we can help, get in touch!