With the classList property of a DOM element, we can add, remove, check, and toggle an element’s class in JavaScript.
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:
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:
We can use the remove
method to remove classes from an element. Take a look at the following code:
To check if there is a class present in a DOM element, we can use the contains
method, as shown below:
To toggle a class, we can use the toggle
method. The toggle
method will:
The toggle
method returns true if the class is added, and false if the class is removed.
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.