classList add, remove, toggle, and contains
Lesson 8 of 38 in the JavaScript learning path.
How do I change classes without rewriting the class attribute?
The class attribute is a string, and rewriting it with className is easy to get wrong. A new string can drop a class that CSS or another script still needs. classList is a token list on the element. add inserts a class if it is missing, remove takes one away, toggle adds it when it is absent and removes it when it is present, and contains reports whether the token is there. Each call changes one token and leaves the others alone.
A module card can use that split cleanly. Toggle is-open when the student shows notes. contains decides whether the notes are open, and add or remove then keeps is-highlighted in agreement. A second button pins the card with add and remove rather than a full attribute rewrite. aria-expanded and aria-pressed follow the same booleans, so the accessible state matches the classes CSS is using. The className string is only read afterward, to show the tokens that remain.
Syntax & Parameters
element.classList.add("is-open");
element.classList.remove("is-open");
element.classList.toggle("is-open");
element.classList.contains("is-open");
Example
Interactive preview available'use strict';
const card = document.querySelector('#module-card');
const toggle = document.querySelector('#toggle-module');
const pin = document.querySelector('#pin-module');
const state = document.querySelector('#class-state');
function paint() {
if (card === null) {
return;
}
const open = card.classList.contains('is-open');
const pinned = card.classList.contains('is-pinned');
if (open) {
card.classList.add('is-highlighted');
} else {
card.classList.remove('is-highlighted');
}
if (toggle !== null) {
toggle.setAttribute('aria-expanded', String(open));
toggle.textContent = open ? 'Hide notes' : 'Show notes';
}
if (pin !== null) {
pin.textContent = pinned ? 'Unpin notes' : 'Pin notes';
pin.setAttribute('aria-pressed', String(pinned));
}
if (state !== null) {
state.textContent = card.className;
}
}
if (toggle !== null && card !== null) {
toggle.addEventListener('click', () => {
card.classList.toggle('is-open');
paint();
console.log(card.className);
});
}
if (pin !== null && card !== null) {
pin.addEventListener('click', () => {
if (card.classList.contains('is-pinned')) {
card.classList.remove('is-pinned');
} else {
card.classList.add('is-pinned');
}
paint();
console.log(card.className);
});
}
paint();
console.log(card === null ? 'missing card' : card.className);
Expected Output
On load, console and #class-state: card After Show notes: card is-open is-highlighted After Pin notes as well: card is-open is-highlighted is-pinned After Hide notes: card is-pinned
Line-by-Line Walkthrough
- The script selects the card, the show button, the pin button, and the state log, each with querySelector.
- paint returns immediately when the card is missing, so later classList calls are not attempted on null.
- contains reads is-open and is-pinned without changing them, and those booleans drive the rest of the paint.
- When the card is open, add puts is-highlighted on it. When it is closed, remove takes is-highlighted off and leaves every other class in place.
- The toggle button receives aria-expanded and a label that says Hide notes or Show notes, matching the open flag.
- The pin button label and aria-pressed follow is-pinned the same way, so the pressed state is not stored only in CSS.
- The state log receives card.className through textContent, which shows the tokens without parsing them as HTML.
- The show button toggles is-open and then calls paint, which reconciles the highlight class and prints the class string.
- The pin button uses contains to choose add or remove for is-pinned, then paints and prints again.
- paint runs once on load, so the log and the console show the starting class string before any click.
Common Pitfalls & Security
className replaces the whole attribute. A write such as card.className = "is-open" drops card, is-pinned, and any other token that layout depends on. classList methods edit one token at a time, but the token still has to be a valid class: spaces split into two classes, and an empty string throws. Toggle also returns a boolean in current browsers, and ignoring that return while also calling contains is fine, as long as you do not toggle twice in one click.
- Setting className from a student string lets that student inject extra class tokens. Keep class names in your script, not in user input.
- card.classList.add("is-open is-highlighted") adds one illegal token with a space in some browsers and throws in others. Add one class per call.
- contains is case sensitive. Is-open does not match is-open.
- Removing a class that is absent is safe. You do not need a contains check before remove.
- Hiding notes with a class is not a security boundary. Do not put secrets in a node that is only hidden with CSS.
Best Practices & Modern Standards
Name state classes for the state they represent, such as is-open or is-pinned, and keep layout classes separate. Drive add, remove, and toggle from one paint function so the highlight class cannot drift away from is-open. Mirror the important states into ARIA attributes in that same function. ES2024 does not replace classList. The token list remains the right tool, and className remains a read-only view of the result.
Prefer toggle for a single on-off class that a button owns. Prefer an explicit contains branch when one class should force another class on or off. Do not rebuild the attribute string by splitting and joining unless you are repairing legacy markup. Test the keyboard focus style, because a button that only changes classes still needs a visible focus ring.
Real-World Use
A course module card hides facilitator notes until the student asks for them. The show button toggles is-open, CSS reveals the notes, and paint adds the highlight so the open card is obvious in a list of modules. Pin keeps the notes open in spirit for the rest of the visit by adding is-pinned without erasing the layout class on the article.
The same card is used on the instructor dashboard. Because the script never replaces className, a theme class added by the page shell survives every toggle. Screen readers hear the expanded state from aria-expanded, which tracks the class instead of a second boolean that could fall out of date.
Frequently Asked Questions
Why not assign className?
className replaces every class on the element with the string you assign. One missing token can break layout or drop a state another button still expects. classList edits a single token and leaves the rest of the attribute alone.
What does toggle return?
It returns true when the class is present after the call and false when it is absent. You can use that boolean for aria-expanded. Calling toggle twice in one click puts the class back where it started, so call it once.
Does remove throw if the class is missing?
No. remove ignores a token that is not on the element. add also ignores a token that is already present, so repeating add does not duplicate the class in the attribute.
Can a student-supplied string become a class?
It should not. Class tokens change presentation and can interact with selectors in ways you did not plan. Keep the token list in your code and put student text in textContent, not in the class attribute.