How to add, remove and toggle CSS classes in JavaScript

published: 26 Aug 2022

2 min read

How to add, remove and toggle CSS classes in JavaScript

As a web developer, you are often required to add, remove, and toggle CSS classes based on the user interactions with elements on the web page. If you had already used jQuery in the past, you'd be probably familiar with the addClass(), removeClass(), and toggleClass() methods.

In modern JavaScript, it makes no sense to load the complete jQuery library just to do some simple DOM manipulations. In this article, you'll learn how to add, remove, and toggle CSS classes in vanilla JavaScript without jQuery.

Using className Property

The simplest way to get as well as set CSS classes in JavaScript is by using the className property. It refers to the value of the HTML element's class attribute.

Let us say we have the following HTML element:

<div>🍕</div>

The following example shows how to add a new CSS class, or replace all existing CSS classes of the above <div> element:

const pizza = document.querySelector('.pizza');

// print existing classes
console.log(pizza.className); // pizza

// add new '.spicy' class
pizza.className += 'spicy';

// replace all existing classes
pizza.className = 'hot spicy pizza';

Since class is a reserved word in JavaScript, the name className is used for this property instead of class. This property is supported by all modern and old browsers, including Internet Explorer.

Using classList Property

There is even a better way to manipulate CSS classes in JavaScript, thanks to the classList property. It is a read-only property that returns a live DOMTokenList collection of all the classes applied to the element.

The classList property works in all modern browsers, and IE10 and above.

You can use the classList property to easily add, remove, and toggle CSS classes from an element in vanilla JavaScript.

Say we have an element like below:

<div>
    🍕
</div>

Let us grab a reference to the above <div> element, and print the existing classes on the console:

// grab element reference
const pizza = document.querySelector('.pizza');

// get all existing classes
console.log(pizza.classList);
// ['hot', 'spicy', 'pizza', value: 'hot spicy pizza']

// get first class name
console.log(pizza.classList[0]); // hot

// get total number of classes
console.log(pizza.classList.length); // 3

Let us now look at the popular methods of the DOMTokenList collection, returned by the classList property. We'll use these methods to manage and update CSS classes for an HTML element.

item() Method

The item() method returns the class in the collection by its index, or undefined if the index is greater than or equal to the list's length property:

console.log(pizza.classList.item(1)); // spicy

add() Method

The add() method adds one or more classes to the HTML element:

pizza.classList.add('sauce', 'cheese', 'tomato');

Now, the element looks like below:

<div>
    🍕
</div>

If you try to add a class that already exists, the add() method will ignore it. To see how it works, let us add more cheese to the pizza:

pizza.classList.add('cheese');

Here is the element now:

<div>
    🍕
</div>

contains() Method

The contains() method returns true if the element contains the given class, otherwise false:

console.log(pizza.classList.contains('cheese')); // true
console.log(pizza.classList.contains('yogurt')); // false

remove() Method

The remove() method is used to remove one or more classes from the element:

pizza.classList.remove('sauce', 'potato');

If you try to remove a class that doesn't exist, as we did in the above example, there won't be any error. JavaScript will simply ignore it.

toggle() Method

toggle() is an interesting method. It removes the class if it already exists, otherwise, it adds it to the collection.

Without this method, you have to manually check if the class exists using contain() before toggling it on or off:

// manual toggle
if (pizza.classList.contains('olive')) {
    pizza.classList.remove('olive');
} else {
    pizza.classList.add('olive');
}

With the toggle() method, you simply pass the name of the class which you want to toggle:

pizza.classList.toggle('olive');

The toggle() method returns true if the class was added, and false if it was removed:

const status = pizza.classList.toggle('olive');

console.log(status); // true -> class was added

You can also pass a second boolean parameter to the toggle() method to indicate whether to add the class or remove it. This will turn toggle() into one way-only operation. If the second argument evaluates to false, then the class will only be removed, but not added. If it evaluates to true, then the class will only be added, but not removed.

Here is an example:

const status = pizza.classList.toggle('hot', false);

console.log(status); // false -> class was removed

replace() Method

The replace() method can be used to replace a CSS class with another class:

pizza.classList.replace('spicy', 'olive');

This method returns true if the target class is successfully replaced with the new class, otherwise false.

The replace() method is currently not supported by Internet Explorer. You can use remove() along with add() to replace a CSS class in older browsers.

forEach() Method

The DOMTokenList collection also supports the forEach() method to iterate over all the classes:

// iterate over all classes
pizza.classList.forEach((item, index) => {
    console.log(item);
});

Conclusion

That's all folks! In this article, we looked at two important properties (className & classList) to manipulate CSS classes in JavaScript.

The className property presents the class attribute of the element and is supported by all browsers including Internet Explorer. It can be used to add a new class or replace existing classes.

On the other hand, the classList property returns a live DOMTokenList collection of all the classes applied to a DOM element. It can be used to easily add, remove, toggle, and iterate through all the classes.

Read Next: Hide and show DOM elements using a CSS class in JavaScript

How to add, remove and toggle CSS classes in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming