JavaScript: classList
The classList property provides methods for adding, removing, checking, and toggling CSS classes on an element.
What you will learn
- When to use
add(),remove(), andtoggle() - How to check for a class with
contains() - How to change visual state without losing meaning or usability
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
- Use class names for presentation and state hooks, not for storing arbitrary data; use
datasetfor small data values. - When a class changes an interactive state, update an accessible state such as
aria-expandedwhen appropriate. classListis read-only as a property reference, but its methods change the element's class attribute.