How to add, remove, toggle class of a DOM element in JavaScript
With the classList property of a DOM element, we can add, remove, check, and toggle an element’s class in JavaScript.
Print the classes of a DOM element
The classList property of a DOM element returns a DOMTokenList, which contains all the classes of the element.
Take a look at the code below:
Add class to an element
We can use the add method to add classes to the element. This is shown below:
The classList contains live data, meaning it will automatically update the class when a class is added or removed:
Remove the class of an element
We can use the remove method to remove classes from an element. Take a look at the following code:
Check if a DOM element contains a certain class
To check if there is a class present in a DOM element, we can use the contains method, as shown below:
Toggle a class
To toggle a class, we can use the toggle method. The toggle method will:
- Add the class if the class is not present in the element.
- Remove the class if the class is present in the element.
The toggle method returns true if the class is added, and false if the class is removed.
Replace a class
To replace an existing class, we can use the replace method.
The replace method returns true if the class was successfully replaced; otherwise, it returns false.