Element: classList property
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since October 2017.
The read-onlyclassList property of theElement interface contains a liveDOMTokenList collection representing theclass attribute of the element. This can then be used to manipulate the class list.
UsingclassList is a convenient alternative to accessing an element's list of classes as a space-delimited string viaelement.className.
In this article
Value
ADOMTokenList object representing the contents of the element'sclass attribute. If theclass attribute is not set or empty, it returns an emptyDOMTokenList, i.e., aDOMTokenList with thelength property equal to0.
Although theclassList property itself is read-only in the sense that you can't replace theDOMTokenList object, you can still assign to theclassList property directly, which is equivalent to assigning to itsvalue property. You can also modify theDOMTokenList object using theadd(),remove(),replace(), andtoggle() methods.
Examples
const div = document.createElement("div");div.classList = "foo"; // forwarded to classList.value// our starting state: <div></div>console.log(div.outerHTML);// use the classList API to remove and add classesdiv.classList.remove("foo");div.classList.add("another-class");// <div></div>console.log(div.outerHTML);// if visible is set remove it, otherwise add itdiv.classList.toggle("visible");// add/remove visible, depending on test conditional, i less than 10div.classList.toggle("visible", i < 10);// falseconsole.log(div.classList.contains("foo"));// add or remove multiple classesdiv.classList.add("foo", "bar", "baz");div.classList.remove("foo", "bar", "baz");// add or remove multiple classes using spread syntaxconst cls = ["foo", "bar"];div.classList.add(...cls);div.classList.remove(...cls);// replace class "foo" with class "bar"div.classList.replace("foo", "bar");Specifications
| Specification |
|---|
| DOM> # ref-for-dom-element-classlist①> |