HTML Element .classList Since: ES6(ECMAScript 2015)
A property for manipulating the class attribute of an HTML element. It provides methods to add, remove, toggle, and check for the existence of classes.
Syntax
// Adds a class.
element.classList.add("className");
// Removes a class.
element.classList.remove("className");
// Removes the class if it exists, or adds it if it does not.
element.classList.toggle("className");
// Checks whether a class exists.
var result = element.classList.contains("className");
Method List
| Method | Description |
|---|---|
| add("className") | Adds the specified class. If the class already exists, nothing happens. You can also add multiple classes at once by separating them with commas. |
| remove("className") | Removes the specified class. Specifying a class that does not exist does not cause an error. You can also remove multiple classes at once by separating them with commas. |
| toggle("className") | Removes the specified class if it exists, or adds it if it does not. Useful for toggling menus open/closed or switching active states. |
| contains("className") | Returns true or false indicating whether the specified class exists. |
Sample Code
<div id="box" class="panel">Box</div> <button id="btn">Toggle</button>
var box = document.querySelector("#box");
// Adds a class.
box.classList.add("active");
// class="panel active"
// Checks whether a class exists.
console.log(box.classList.contains("active")); // Outputs 'true'.
// Toggles a class on button click.
var btn = document.querySelector("#btn");
btn.addEventListener("click", function() {
box.classList.toggle("highlight");
});
// Adds multiple classes at once.
box.classList.add("rounded", "shadow");
// Removes a class.
box.classList.remove("panel");
Overview
element.classList is a property for safely and easily manipulating the class attribute of an HTML element. Previously, you had to directly manipulate a string using the element.className property, but the methods on element.classList make it straightforward to add and remove individual classes.
The toggle() method in particular is handy for switching UI states. Operations such as opening and closing menus, switching active tabs, or toggling dark mode — any "on/off" state switch — can be written in a single line.
Because add() and remove() do not throw an error when you add or remove a class that does not exist, there is no need to check for the class beforehand.
Browser Compatibility
21 ×
20 △
19 △
18 △
17 △
16 △
13 △
12 △
11 △
10 △
9 △
8 △
7 or earlier ×
3.5 or earlier ×
6 or earlier ×
11 or earlier ×
Android Browser
37+ ○
4 ×
3.4 △
3 △
2.4 or earlier ×
Chrome Android
36+ ○
24 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.