Syntax
element.classList.add("class")
element.classList.toggle("class")Examples
Adding and Removing Classes
Basic class manipulation.
const box = document.querySelector("#box");
box.classList.add("active");
box.classList.add("highlighted", "large"); // multiple at once
box.classList.remove("large");
console.log(box.className); // "active highlighted"toggle() - The Common UI Pattern
Switching a class on or off, ideal for things like dropdown menus or active states.
const menuButton = document.querySelector("#menuToggle");
const menu = document.querySelector("#menu");
menuButton.addEventListener("click", () => {
menu.classList.toggle("open"); // adds if absent, removes if present
});
// Force a specific state regardless of current state
menu.classList.toggle("open", true); // always add
menu.classList.toggle("open", false); // always removecontains() - Checking Current State
Testing whether an element currently has a specific class.
const panel = document.querySelector("#panel");
if (panel.classList.contains("collapsed")) {
console.log("Panel is currently collapsed");
} else {
console.log("Panel is currently expanded");
}Best practices
- Use classList methods instead of manually manipulating element.className as a string - they handle spacing and duplicates correctly
- Use toggle() for on/off UI states like open/closed menus or active/inactive buttons rather than manually checking and calling add()/remove()
- Pass the optional second argument to toggle() when you need to force a specific state rather than simply flip the current one
- Prefer toggling classes (with the actual styling in CSS) over directly manipulating element.style, for cleaner separation of concerns
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification