Add, Remove, Toggle CSS Classes With Pure Vanilla JavaScript

In javascript on 2~3 minutes
Add, Remove, Toggle CSS Classes With Pure Vanilla JavaScript

Usually, JavaScript frameworks and libraries like jQuery provide their own implementations to manipulate CSS classes in an HTML document. But what if you do not use any of these frameworks or libraries. So, let’s see how to add, remove and toggle CSS classes only using pure vanilla JavaScript.

We are using the getElementById() method for the following examples to select HTML DOM (Document Object Model) elements. However, you can also use methods like querySelector() and other methods as explained in how to select HTML elements.

Add Classes

First, we are going to add classes to the list items. Add the following code into the script tag. It will add the color-red class to the element which has the list-a id. Likewise, it will add other classes as well. You can open the HTML file in a browser to see changes.

document.getElementById("list-a").classList.add('color-red');
document.getElementById("list-b").classList.add('color-green');
document.getElementById("list-c").classList.add('color-blue');

You can also add multiple classes like below.

document.getElementById("list-a").classList.add('color-red', 'border-dash');

Remove Classes

The following code will remove the border-solid class from the element which has the list-b id.

document.getElementById("list-b").classList.remove('border-solid');

As usual, you can remove multiple classes like we did when we added classes.

Toggle Classes

The following code will add the border-dash class to the element if it does not exist in the element which has the list-a id. If there is no such class for that element, it will add the border-dash class to the element.

document.getElementById("list-a").classList.toggle('border-dash');

In addition to that, we can add a second boolean parameter to forcefully add or remove a particular class regardless of its availability. The following code will remove the color-red class from the element.

document.getElementById("list-a").classList.toggle('color-red', false);

This will add the color-blue to list-a element.

document.getElementById("list-a").classList.toggle('color-blue, true);