Manipulating CSS Classes with JavaScript classList API
The classList property in JavaScript provides a modern,
efficient way to dynamically manipulate CSS class tokens on DOM
elements. As a read-only property returning a live
DOMTokenList collection, it eliminates the need for manual
string manipulation of element.className. By exposing
dedicated methods such as add(), remove(),
toggle(), replace(), and
contains(), the classList API allows
developers to alter element styling and state cleanly, safely, and with
minimal code.
Understanding the DOMTokenList
When you access element.classList, the browser returns a
DOMTokenList. This interface represents a set of
space-separated tokens—in this case, individual class names assigned to
the element. Because it functions as an indexed, iterable collection
with built-in validation, it automatically handles edge cases like
ignoring duplicates, trimming whitespace, and throwing errors if invalid
characters (such as spaces within a token) are provided.
Key Methods for Manipulating Class Tokens
The API exposes five core methods to alter and query class tokens dynamically:
1. add(...tokens)
Appends one or more class tokens to the element. If a specified class already exists on the element, the method ignores it, preventing duplicate class names.
const element = document.querySelector('.card');
element.classList.add('active');
element.classList.add('highlighted', 'visible'); // Adds multiple classes2. remove(...tokens)
Removes one or more specified class tokens from the element. If a class does not exist, no error is thrown; the token is simply ignored.
element.classList.remove('active');
element.classList.remove('highlighted', 'visible'); // Removes multiple classes3. toggle(token, force)
Toggles the presence of a class token. If the token exists, it is removed; if it does not exist, it is added.
The optional second parameter (force) accepts a boolean:
* If true, the class is added regardless of whether it
already exists. * If false, the class is removed.
// Basic toggle
element.classList.toggle('hidden');
// Conditional toggle using the force argument
const isModalOpen = true;
element.classList.toggle('open', isModalOpen); // Adds 'open' if true, removes if false4.
replace(oldToken, newToken)
Replaces an existing class token with a new one. It returns a boolean
value: true if oldToken was successfully
replaced, and false if oldToken was not found
on the element.
const wasReplaced = element.classList.replace('theme-light', 'theme-dark');5. contains(token)
Checks whether the specified class token exists on the element,
returning true or false. This is ideal for
conditional logic based on UI state.
if (element.classList.contains('error')) {
console.log('Element currently has an error state.');
}Why Use classList Over className?
Before the introduction of classList, dynamic class
manipulation relied on reading and rewriting the
element.className string. This approach required regular
expressions or array operations (like split(' ') and
join(' ')) to avoid accidentally corrupting adjacent
classes or adding duplicates.
The classList API offers several distinct advantages: *
Safety: Prevents accidental overwrites of existing
classes. * Clarity: Uses semantic method names rather
than string operations. * Performance: Operates
natively at the browser level without requiring custom string parsing. *
Multiple Arguments: Methods like add() and
remove() accept rest parameters to modify multiple tokens
in a single execution.