Changing the look of an element from JavaScript almost never means writing colors and margins by hand. It means putting a class on or taking it off, and letting the stylesheet do the rest.
That separation rests on a quiet object, present on every element: classList.
Definition
classList is a view over the class attribute of an element, shaped as a list of words. It exposes methods that add or remove one class without touching the others, and it mirrors the real state of the element at any moment.
const card = document.querySelector(".card");
card.classList.add("open");
card.classList.remove("hidden");
console.log(card.classList.contains("open")); // true
console.log(card.classList.length);The five methods
| Method | What it does |
|---|---|
add | Adds one or more classes, never duplicating |
remove | Removes one or more classes, no error when absent |
toggle | Adds the class when missing, removes it otherwise |
contains | Hands back a Boolean telling whether the class is there |
replace | Swaps one class for another in a single call |
Names go in separately: add("a", "b") adds two classes, while add("a b") throws, since a space is forbidden inside a class name.
toggle and its second argument
A second boolean argument forces the outcome: true adds, false removes. The method then mirrors a state directly, which saves a three-line if.
const panel = document.querySelector("#panel");
const isOpen = false;
panel.classList.toggle("visible", isOpen); // removes "visible"
const present = panel.classList.toggle("visible");
console.log(present); // true: the class was just addedWith no second argument, the returned value tells whether the class is present after the call.
Why not className
className is the whole attribute string. Writing to it replaces everything, including classes placed by another part of the code or by the server.
// <div class="card shadow selected">
card.className = "open"; // the three classes disappear
card.classList.add("open"); // the three classes remainReading it stays handy at times, for instance to log the state of an element in the console. For any change, classList is the right answer.
Frequently asked questions
Should presence be checked before adding?
No, add ignores a class already there and remove ignores a class that is absent. Both methods are no-ops in those cases, which makes any prior test pointless. contains is there to decide something else, not to guard the call.
How do you get the list of classes?
The Spread (...) operator turns it into an Array, which opens up map and filter. The value property hands back the full string instead, identical to className, handy for a log line or a quick comparison.
Is changing style directly a better idea?
Rarely. A value written into style becomes an inline style, which outranks the stylesheet and grows hard to undo. A class keeps the styling in the same place as the rest of the CSS. style stays justified for a computed value, such as a position in pixels.