How to manipulate an element's classes in vanilla JS

In jQuery, there are several methods that allow you to manipulate the classes on an element. These are addClass(), removeClass(), toggleClass(), and hasClass(). Let’s look at how we can do these things using vanilla JS, and also how to replace a class—a method that jQuery lacks!

A note before we begin: you can and should still use the older className property if it’s appropriate, but this post focuses on some newer methods available to the classList property.

For each of the following examples, let’s imagine you’ve selected an element and saved it to a variable called app. You would call all of the following methods on the element’s classList property.

Adding classes

To add a class, you can use the DOMTokenList.add() method.

// Add a class

Removing classes

To remove a class, you can use the DOMTokenList.remove() method.

// Remove a class

Toggling classes

To toggle a class, you can use the DOMTokenList.toggle() method.

// Toggle a class

Checking if an element has a class

To check for a class, you can use the DOMTokenList.contains() method.

if (app.classList.contains("bg-blue")) {
  // Do something if the element has a class

Replacing classes

To replace a class, you can use the DOMTokenList.replace() method.

This method, unlike the others in this post, accepts two arguments: the former being the old class, and the latter being the new class.

// Replace .bg-blue with .bg-red
app.classList.replace("bg-blue", "bg-red");

Browser compatibility

The classList property is supported in all modern browsers, and IE10 and above. There are a few minor caveats, mostly for IE, so be sure to check the full browser compatibility information if this affects you.

If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!