HTML DOM Element classList
Example
Add a "myStyle" class to an element:
list.add("myStyle");
Remove the "myStyle" class from an element:
list.remove("myStyle");
Toggle "myStyle" on and off:
list.toggle("myStyle");
More examples below.
Description
The classList property returns the CSS classnames of an element.
The classList property returns a
DOMTokenList.
See Also:
Syntax
Return Value
A list of the class names of an element.
Note
The classList property is read-only,
but you can use the methods listed below, to add, toggle or remove CSS classes from the list:
classList Properties and Methods
| Name | Description |
|---|---|
| add() | Adds one or more tokens to the list |
| contains() | Returns true if the list contains a class |
| entries() | Returns an Iterator with key/value pairs from the list |
| forEach() | Executes a callback function for each token in the list |
| item() | Returns the token at a specified index |
| keys() | Returns an Iterator with the keys in the list |
| length | Returns the number of tokens in the list |
| remove() | Removes one or more tokens from the list |
| replace() | Replaces a token in the list |
| supports() | Returns true if a token is one of an attribute's supported tokens |
| toggle() | Toggles between tokens in the list |
| value | Returns the token list as a string |
| values() | Returns an Iterator with the values in the list |
More Examples
Add multiple classes to the an element:
Remove multiple classes from an element:
Get the class names of the "myDIV" element:
<p>I am myDIV.</p>
</div>
const list = document.getElementById("myDIV").classList;
Does an an element has a "myStyle" class?
Remove "anotherClass" if an element has a "myStyle" class.
element.classList.remove("anotherClass");
}
Toggle between classes to create a dropdown button:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
Create a sticky navigation bar:
const navbar = document.getElementById("navbar");
// Get the offset position of the navbar
const sticky = navbar.offsetTop;
// Add the sticky class to the navbar when you reach its scroll position
// Remove it when you leave the scroll position
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
Browser Support
element.classList is supported in all browsers:
| Chrome | IE | Edge | Firefox | Safari | Opera |
| Yes | 10-11 | Yes | Yes | Yes | Yes |