JavaScriptEasy
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>`;56const panel = document.getElementById("panel");7const button = document.getElementById("toggle");89panel.classList.add("rounded", "shadow");10console.log([...panel.classList]); // ["panel", "theme-light", "rounded", "shadow"]1112button.addEventListener("click", () => {13 const isOpen = panel.classList.toggle("is-open"); // returns the new state14 button.setAttribute("aria-expanded", String(isOpen)); // keep accessibility in sync15});16button.click();17console.log(panel.classList.contains("is-open"), button.getAttribute("aria-expanded")); // true "true"1819// Force a state from a condition20const hasError = false;21panel.classList.toggle("has-error", hasError);2223// Swap a theme class24panel.classList.replace("theme-light", "theme-dark");25console.log(panel.className); // "panel theme-dark rounded shadow is-open" - replace keeps the position2627// 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.