JavaScript: classList

The classList property provides methods for adding, removing, checking, and toggling CSS classes on an element.

What you will learn

Minimal example

const panel = document.querySelector("#panel");
const button = document.querySelector("#toggle");

button.addEventListener("click", () => {
  panel.classList.toggle("is-open");
  const open = panel.classList.contains("is-open");
  button.setAttribute("aria-expanded", String(open));
});

add() inserts a class, remove() deletes it, contains() checks it, and toggle() switches it. The optional second argument to toggle() can force the class on or off.

Important points