The DOMTokenList
interface represents a set of space-separated tokens. Such a set is returned by Element.classList
or HTMLLinkElement.relList
, and many others.
A DOMTokenList
is indexed beginning with 0
as with JavaScript Array
objects. DOMTokenList
is always case-sensitive.
In the following simple example, we retrieve the list of classes set on a <p>
element as a DOMTokenList
using Element.classList
, add a class using DOMTokenList.add()
, and then update the Node.textContent
of the <p>
to equal the DOMTokenList
.
First, the HTML:
Now the JavaScript:
let para = document.querySelector("p");
let classes = para.classList;
para.classList.add("d");
para.textContent = `paragraph classList is "${classes}"`;
The output looks like this:
Methods that modify the DOMTokenList
(such as DOMTokenList.add()
) automatically trim any excess Whitespace and remove duplicate values from the list. For example:
<span class=" d d e f"></span>
let span = document.querySelector("span");
let classes = span.classList;
span.classList.add("x");
span.textContent = `span classList is "${classes}"`;
The output looks like this: