Codectionary / Developer documentation / JavaScript

classList: add, remove, toggle, contains

The classList property provides a convenient API for managing an element's CSS classes without manually parsing the className string. add() and remove() add or remove one or more classes, toggle() switches a class on or off based on its current presence, and contains() checks whether a class is currently applied.

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 remove

contains() - 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