Element: classList property
The Element.classList
is a read-only property that returns a live DOMTokenList
collection of the class
attributes of the element. This can then be used to manipulate the class list.
Using classList
is a convenient alternative to accessing an element's list of classes as a space-delimited string via element.className
.
Value
A DOMTokenList
representing the contents of the element's class
attribute. If the class
attribute is not set or empty, it returns an empty DOMTokenList
, i.e. a DOMTokenList
with the length
property equal to 0
.
Although the classList
property itself is read-only, you can modify its associated DOMTokenList
using the add()
, remove()
, replace()
, and toggle()
methods.
You can test whether the element contains a given class using the classList.contains()
method.
Examples
const div = document.createElement("div");
div.className = "foo";
console.log(div.outerHTML);
div.classList.remove("foo");
div.classList.add("anotherclass");
console.log(div.outerHTML);
div.classList.toggle("visible");
div.classList.toggle("visible", i < 10);
console.log(div.classList.contains("foo"));
div.classList.add("foo", "bar", "baz");
div.classList.remove("foo", "bar", "baz");
const cls = ["foo", "bar"];
div.classList.add(...cls);
div.classList.remove(...cls);
div.classList.replace("foo", "bar");
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
classList |
22
8–22Not supported for SVG elements.
|
16
12–16Not supported for SVG elements.
|
3.6 |
10Not supported for SVG elements.
|
11.5 |
7
6–7Not supported for SVG elements.
|
4.4
3–4.4Not supported for SVG elements.
|
25
18–25Not supported for SVG elements.
|
4 |
11.5 |
7
6–7Not supported for SVG elements.
|
1.5
1.0–1.5Not supported for SVG elements.
|
See also