What is classList?

element.classList is a live list of an element's CSS classes with methods to add, remove, toggle, replace and check classes, which is far safer than editing the className string by hand.

Methods

  • add("a", "b"): adds one or more classes (no duplicates).
  • remove("a", "b"): removes classes (no error if missing).
  • toggle("open"): adds if missing, removes if present; returns the new state.
  • toggle("open", condition): forces add (true) or remove (false). Ideal for syncing a class with state.
  • contains("open"): checks for a class.
  • replace("old", "new"): swaps one class for another.
  • It is iterable, and length/item(i) work too.

Why prefer it over className

element.className = "active" overwrites every other class. Concatenating strings leads to duplicates and spacing bugs. classList changes only what you ask.

Good practice

  • Toggle classes and let CSS handle appearance and transitions, instead of setting many inline styles.
  • Keep state classes clearly named (is-open, is-loading, has-error).
  • For accessibility, pair visual classes with ARIA attributes (aria-expanded, aria-hidden), because screen readers do not see classes.

SVG

classList works on SVG elements too, where className is an object rather than a string.

Code example

js
1document.body.innerHTML = `
2 <style>.panel{display:none}.panel.is-open{display:block}</style>
3 <button id="toggle" aria-expanded="false">Menu</button>
4 <nav id="panel" class="panel theme-light">Links</nav>`;
5
6const panel = document.getElementById("panel");
7const button = document.getElementById("toggle");
8
9panel.classList.add("rounded", "shadow");
10console.log([...panel.classList]); // ["panel", "theme-light", "rounded", "shadow"]
11
12button.addEventListener("click", () => {
13 const isOpen = panel.classList.toggle("is-open"); // returns the new state
14 button.setAttribute("aria-expanded", String(isOpen)); // keep accessibility in sync
15});
16button.click();
17console.log(panel.classList.contains("is-open"), button.getAttribute("aria-expanded")); // true "true"
18
19// Force a state from a condition
20const hasError = false;
21panel.classList.toggle("has-error", hasError);
22
23// Swap a theme class
24panel.classList.replace("theme-light", "theme-dark");
25console.log(panel.className); // "panel theme-dark rounded shadow is-open" - replace keeps the position
26
27// className overwrites everything (usually a bug)
28panel.className = "panel";
29console.log(panel.classList.length); // 1

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app