Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

DOMTokenList: Adding and removing tokens

Use `add()` and `remove()` to update individual tokens, such as an element’s class names, without replacing the whole attribute. Learn when an invalid token makes the call fail.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

tokenList.add(...tokens);
tokenList.remove(...tokens);

DOMTokenList.add/remove refers to two instance methods on an ordered, case-sensitive set of unique tokens. element.classList gives you a live list backed by the class attribute: editing the list updates the attribute, and editing the attribute is visible through a list reference you already saved. Other properties, such as HTMLLinkElement.relList, also return a DOMTokenList.

add() appends missing tokens in argument order without creating duplicates. remove() deletes matching tokens and ignores valid tokens that are absent. Both methods accept zero or more tokens and return undefined on success. With no arguments, membership stays the same, but writing the attribute back can normalize its spacing and remove duplicates from its text.

Pass each class name as a separate string: element.classList.add("a", "b"), not element.classList.add("a b"). Use the class name ("a"), not a CSS selector (".a"). Both methods validate all tokens before changing the list. An empty string ("") throws a DOMException named SyntaxError; a token containing ASCII whitespace, such as a space or tab, throws one named InvalidCharacterError. In either case, even an earlier valid token in the same call is not applied.

element.classList.remove() removes tokens, not the element itself. element.remove() detaches the element from its parent. DOMTokenList is a web-platform DOM interface, not part of ECMAScript 2024. Check that your target runtime provides the DOM APIs you need.

Examples

{
  const card = typeof document === "undefined"
    ? createClassOnlyCard()
    : document.createElement("div");
  card.setAttribute("class", "card is-loading");
  const tokens = card.classList;

  tokens.add("is-active", "is-ready", "is-active");
  console.log(card.getAttribute("class"));

  tokens.remove("is-loading", "missing");
  console.log(card.getAttribute("class"));

  try {
    tokens.add("pending", "two words");
  } catch (error) {
    console.log(error.name);
  }

  try {
    tokens.remove("card", "");
  } catch (error) {
    console.log(error.name);
  }

  console.log(card.getAttribute("class"));

  // Without a DOM, model only the class attribute and the operations used here.
  function createClassOnlyCard() {
    let value = null;
    const asciiWhitespace = /[\t\n\f\r ]+/;

    function update(tokens, apply) {
      for (const token of tokens) {
        if (token === "") {
          throw new DOMException("A token must not be empty.", "SyntaxError");
        }
        if (asciiWhitespace.test(token)) {
          throw new DOMException("A token must not contain ASCII whitespace.", "InvalidCharacterError");
        }
      }

      const classes = new Set((value ?? "").split(asciiWhitespace).filter(Boolean));
      for (const token of tokens) apply(classes, token);
      if (value !== null || classes.size > 0) value = [...classes].join(" ");
    }

    return {
      setAttribute(name, text) {
        if (name === "class") value = String(text);
      },
      getAttribute(name) {
        return name === "class" ? value : null;
      },
      classList: {
        add(...tokens) {
          update(tokens, (classes, token) => classes.add(token));
        },
        remove(...tokens) {
          update(tokens, (classes, token) => classes.delete(token));
        },
      },
    };
  }
}

Result

card is-loading is-active is-ready
card is-active is-ready
InvalidCharacterError
SyntaxError
card is-active is-ready

Run this in a browser console to use native `classList`. The element is not inserted into the document. In Node.js, the example uses a local model of the `class` attribute and the operations shown here instead of the DOM. The final line shows that after both failed calls, `pending` is still absent and `card` is still present.

Related lessons

  • JavaScript · Lesson 1 · Advanced · Version: 4
  • JavaScript · Lesson 2 · Advanced · Version: 4
  • JavaScript · Lesson 3 · Advanced · Version: 4
  • JavaScript · Lesson 4 · Advanced · Version: 4
  • JavaScript · Lesson 5 · Advanced · Version: 4
  • JavaScript · Lesson 6 · Advanced · Version: 4
  • JavaScript · Lesson 8 · Advanced · Version: 4
  • JavaScript · Lesson 12 · Advanced · Version: 4
  • JavaScript · Lesson 13 · Advanced · Version: 4
  • JavaScript · Lesson 16 · Advanced · Version: 4
  • JavaScript · Lesson 18 · Advanced · Version: 4
  • JavaScript · Lesson 19 · Advanced · Version: 4
  • JavaScript · Lesson 22 · Advanced · Version: 4
  • JavaScript · Lesson 23 · Advanced · Version: 4
  • JavaScript · Lesson 26 · Advanced · Version: 4
  • JavaScript · Lesson 28 · Advanced · Version: 4
  • JavaScript · Lesson 29 · Advanced · Version: 4
  • JavaScript · Lesson 32 · Advanced · Version: 4
  • JavaScript · Lesson 33 · Advanced · Version: 4
  • JavaScript · Lesson 36 · Advanced · Version: 4
  • JavaScript · Lesson 37 · Advanced · Version: 4
  • JavaScript · Lesson 39 · Advanced · Version: 4
  • JavaScript · Lesson 40 · Advanced · Version: 4
  • JavaScript · Lesson 41 · Advanced · Version: 4
  • JavaScript · Lesson 45 · Advanced · Version: 4
  • JavaScript · Lesson 27 · Intermediate · Version: 3
  • JavaScript · Lesson 28 · Intermediate · Version: 3
  • JavaScript · Lesson 29 · Intermediate · Version: 3
  • JavaScript · Lesson 30 · Intermediate · Version: 3
  • JavaScript · Lesson 35 · Intermediate · Version: 3
  • JavaScript · Lesson 38 · Intermediate · Version: 3
  • JavaScript · Lesson 39 · Intermediate · Version: 3
  • JavaScript · Lesson 41 · Intermediate · Version: 3
  • JavaScript · Lesson 42 · Intermediate · Version: 3

Sources