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
At a glance
- Purpose
- Application logic and interaction
- File extension
- .js ยท .mjs
- Runs in
- Browsers and JavaScript runtimes
- Usually used with
- HTML, CSS and Web APIs
Specifications & further reading
Related JavaScript documentation
DOM Selection: querySelector(), getElementById()
These methods find elements in the DOM. getElementById() finds a single element by its unique id, generally the fastest option. querySelector() finds the first element matching any valid CSS selector, and querySelectorAll() returns all matching elements as a static NodeList.Creating and Modifying Elements
createElement() builds a new DOM element in memory, which can then be customized and inserted into the page with methods like appendChild() or append(). textContent sets plain text safely, while innerHTML parses and inserts HTML markup - which carries injection risks if the content includes untrusted user input.IntersectionObserver
IntersectionObserver efficiently detects when an element enters or exits the viewport (or another container), without the performance cost of manually listening to scroll events and calculating positions. It is the standard tool for lazy-loading images, infinite scroll, and scroll-triggered animations.MutationObserver
MutationObserver watches for changes to the DOM tree - added/removed elements, attribute changes, or text content changes - and runs a callback in response. It is useful for reacting to DOM changes made by other scripts or third-party widgets that you do not directly control.
These methods find elements in the DOM. getElementById() finds a single element by its unique id, generally the fastest option. querySelector() finds the first element matching any valid CSS selector, and querySelectorAll() returns all matching elements as a static NodeList.Creating and Modifying Elements
createElement() builds a new DOM element in memory, which can then be customized and inserted into the page with methods like appendChild() or append(). textContent sets plain text safely, while innerHTML parses and inserts HTML markup - which carries injection risks if the content includes untrusted user input.IntersectionObserver
IntersectionObserver efficiently detects when an element enters or exits the viewport (or another container), without the performance cost of manually listening to scroll events and calculating positions. It is the standard tool for lazy-loading images, infinite scroll, and scroll-triggered animations.MutationObserver
MutationObserver watches for changes to the DOM tree - added/removed elements, attribute changes, or text content changes - and runs a callback in response. It is useful for reacting to DOM changes made by other scripts or third-party widgets that you do not directly control.