How does classList.toggle() work in JavaScript?

BeginnerBrowser and web interview questionBy , updated 24 November 2026

Short answer

element.classList.toggle("open") removes the class open if the element has it and adds it if it does not, then returns true if the class is present afterwards and false if not. Pass a second argument, toggle("open", isOpen), and it becomes one-way: true only adds, false only removes. That is the clean way to keep a class in sync with state.

classList is a live DOMTokenList

element.classList is not an array and not a copy. It is a DOMTokenList: a live view of the element's class attribute, split into tokens. Change the attribute any other way, with className or setAttribute, and the same classList object shows the new tokens at once. Change it through classList, and the attribute is rewritten.

const el = document.querySelector(".card");
const list = el.classList;

el.className = "card featured";
list.length;          // 2, the same object sees the change
list.value;           // "card featured"
[...list];            // ["card", "featured"], it is iterable
list.forEach((c) => console.log(c));

The class attribute stays the source of truth, which is the attribute and property relationship explained in attributes vs properties in the DOM. Because classList is array-like rather than an array, you spread it or use Array.from before calling map or filter; see array-like objects in JavaScript.

add and remove take several tokens

el.classList.add("is-active", "has-shadow"); // names already present are skipped
el.classList.remove("is-active", "is-loading"); // missing names are ignored

Neither returns anything. Both rewrite the attribute in a normalised form: each token once, in order, separated by single spaces. So class=" a b a " becomes class="a b" after add("a"), even though nothing was added. If the element has no class attribute and the result is empty, remove does not create one.

toggle and its return value

const open = menu.classList.toggle("open");
// open === true  -> the class was added
// open === false -> the class was removed

The return value tells you the state after the call, so you can use it directly instead of calling contains again. Unlike add and remove, toggle takes only one token.

The force argument

menu.classList.toggle("open", true);  // add if missing, otherwise leave it, returns true
menu.classList.toggle("open", false); // remove if present, otherwise leave it, returns false
row.classList.toggle("is-selected", selectedIds.has(row.dataset.id));

With force, toggle stops flipping and sets the class to match a condition. This is better than the if/else version for three reasons:

  • It is one expression. toggle("is-stuck", !entry.isIntersecting) replaces four lines of if (x) add else remove.
  • It is idempotent. Running it twice with the same condition gives the same result. A bare toggle() called from two places, or twice by a duplicated event listener, drifts out of sync with your state.
  • State drives the UI. The class follows a value you own, such as isOpen, instead of the DOM being the only record of whether something is open.

Two details. force is converted to a boolean, so toggle("x", 0) removes and toggle("x", "yes") adds. But undefined counts as not passing the argument at all, so toggle("x", maybeUndefined) flips the class. Convert explicitly with Boolean(value) when the condition might be missing.

contains and replace

el.classList.contains("open");               // true or false
el.classList.replace("theme-light", "theme-dark"); // true if theme-light was there

contains matches whole tokens and is case-sensitive: "btn" is not found in class="btn-primary", and "Active" is not "active". It never throws, and returns false for an empty string.

replace(oldToken, newToken) swaps one token for another in the same position and returns true. If oldToken is not present, it changes nothing and returns false; it does not add newToken. That makes it a safe way to switch between mutually exclusive classes such as themes or sizes. It is supported in all current browsers, and has been since Chrome 61, Firefox 49 and Safari 10.1.

Errors: empty strings and whitespace

Tokens cannot be empty and cannot contain ASCII whitespace (space, tab, line feed, form feed, carriage return). add, remove, toggle and replace check this and throw a DOMException:

Call Error name
add(""), remove(""), toggle(""), replace("a", "") SyntaxError
add("a b"), toggle("is open") InvalidCharacterError

add and remove check every token before changing anything, so one bad name in add("a", "") means no class is added. The common cause is passing a whole class string: split it first, for example el.classList.add(...names.split(/\s+/).filter(Boolean)). A non-breaking space is not ASCII whitespace, so it does not throw and becomes part of the class name.

className vs classList

className is the class attribute as one string. Assigning to it replaces every class, so el.className += " active" works but can duplicate a class, and removing one means string surgery. classList edits individual tokens. Use className (or el.classList.value) when you want to set the whole list at once, and classList for everything else.

On SVG elements, className is not a string but an SVGAnimatedString, so svg.className.includes("icon") fails. classList lives on Element, so it works the same on <svg>, <path> and other SVG elements. If you need the raw string on SVG, use getAttribute("class").

An accessible toggle

A class only changes how something looks. Screen readers need the state too, so set the class and aria-expanded from the same value:

<button type="button" class="nav-toggle" aria-expanded="false" aria-controls="site-nav">Menu</button>
<nav id="site-nav" class="site-nav">…</nav>
const button = document.querySelector(".nav-toggle");
const nav = document.getElementById(button.getAttribute("aria-controls"));

function setOpen(open) {
  button.setAttribute("aria-expanded", String(open));
  nav.classList.toggle("is-open", open);
}

button.addEventListener("click", () => {
  setOpen(button.getAttribute("aria-expanded") !== "true");
});
.site-nav:not(.is-open) { display: none; } /* display: none also hides it from screen readers */

setOpen uses force, so the class and the attribute cannot disagree, and closing on Escape or on route change is just setOpen(false). Use a real <button> so keyboard and screen reader users can operate it; what ARIA is and when to use it explains why the attribute matters. You could also style straight from [aria-expanded="true"] and skip the class entirely. Build an accessible accordion with keyboard navigation applies the same idea to several panels.

Practise it

Interviewers sometimes ask you to rebuild these methods without classList, which forces you to handle whitespace, whole-token matching and the errors above. Re-implement classList.contains, add, remove and toggle by parsing the class attribute is exactly that exercise, and Build a chainable, jQuery-style DOM wrapper asks for a toggleClass(name, force) across many elements.

Follow-up questions interviewers ask

What does classList.toggle return?

A boolean: true if the token is in the list after the call, false if it is not. With force, it returns force converted to a boolean.

Can toggle take more than one class?

No. toggle takes one token and an optional force. To toggle several, call it once per class, ideally with the same force so they stay together.

Why prefer toggle(name, condition) over if/else with add and remove?

It is shorter, it gives the same result however many times it runs, and it ties the class to your state instead of to the current DOM.

Is classList faster than className?

For a single change, the difference does not matter. What matters is that classList avoids string bugs, and that batching reads and writes of layout properties around class changes avoids forced reflows.

Why does classList.add("a b") throw?

Class names cannot contain whitespace, because whitespace is the separator in the class attribute. The browser throws an InvalidCharacterError rather than silently adding two classes.

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Re-implement classList.contains, add, remove and toggle by parsing the class attributeEasy20 min
  2. Build a chainable, jQuery-style DOM wrapperEasy25 min
  3. Build an accessible accordion with keyboard navigationMedium35 min
  4. Implement getElementsByClassName() recursivelyEasy15 min
  5. List every class name used on a page with a recursive DOM walkEasy20 min