To check whether a DOM element has a specific CSS class in JavaScript, validate that the target is a DOM Element and the class name is a non-empty token without whitespace, then call element.classList.contains(className). classList.contains() checks exact class tokens rather than raw substrings, handles multiple whitespace-separated classes cleanly, and performs a pure read without mutating the DOM.
1. Checking a Class Token Safely with element.classList.contains()
Guard against non-Element values (null, undefined, text nodes, or plain objects), reject empty or multi-token strings passed as a single class name, and return a strict boolean without mutating the element:
// Safely check whether a DOM Element contains a specific CSS class token
function hasCssClass(element, className) {
if (!(element instanceof Element)) {
throw new TypeError("Expected element to be a DOM Element.");
}
if (typeof className !== "string") {
throw new TypeError("Expected className to be a string.");
}
const trimmed = className.trim();
if (trimmed === "" || /\s/.test(trimmed)) {
throw new RangeError("Expected className to be a single non-empty CSS class token.");
}
return element.classList.contains(trimmed);
}
// Example usage:
// const bannerEl = document.getElementById("alert-banner");
// console.log("Is active?", hasCssClass(bannerEl, "is-active"));
- Exact token matching:
element.classList.contains("active")returnstrueonly when"active"is a standalone class token on the element. - Pure read & non-mutating: Reads
classListwithout altering attributes or class state.
2. Checking Multiple Classes (Any Match vs. All Required)
When you need to check whether an element has at least one class from a list or every class from a required set, validate each token and evaluate with .some() or .every() over element.classList:
// Check whether a DOM Element has any or all specified CSS class tokens
function hasAnyOrAllClasses(element, classNames, { mode = "all" } = {}) {
if (!(element instanceof Element)) {
throw new TypeError("Expected element to be a DOM Element.");
}
if (!Array.isArray(classNames) || classNames.length === 0) {
throw new TypeError("Expected classNames to be a non-empty Array of class strings.");
}
const normalizedTokens = classNames.map((name) => {
if (typeof name !== "string") {
throw new TypeError("Each class name must be a string.");
}
const token = name.trim();
if (token === "" || /\s/.test(token)) {
throw new RangeError(`Invalid CSS class token: "${name}"`);
}
return token;
});
if (mode === "any") {
return normalizedTokens.some((token) => element.classList.contains(token));
}
return normalizedTokens.every((token) => element.classList.contains(token));
}
// Example usage:
// const cardEl = document.querySelector(".product-card");
// console.log("Has both card and featured:", hasAnyOrAllClasses(cardEl, ["card", "featured"], { mode: "all" }));
// console.log("Has any status class:", hasAnyOrAllClasses(cardEl, ["is-soldout", "is-draft"], { mode: "any" }));
- Explicit
allvsanymodes: Avoids ambiguity when testing multiple classes at once. - Input array untouched: Maps and reads without mutating the caller’s
classNamesarray or the DOM node.
3. Common Traps to Avoid
Checking whether a DOM element has a CSS class in JavaScript often runs into a few pitfalls:
- Using substring matching on
element.className(el.className.includes("btn")): A class like"btn-outline"or"icon-btn"contains"btn"as a substring even though"btn"is not present as a class token. - Calling
.classListonnullor non-Elementnodes:document.querySelector(".missing")returnsnull, andnull.classList.contains(...)throwsTypeError: Cannot read properties of null—always checkelement instanceof Elementfirst. - Passing multiple space-separated classes into
.classList.contains("a b"):classList.contains()expects a single class token and returnsfalse(or throws aDOMExceptionon empty/whitespace tokens in some contexts) rather than checking both"a"and"b".
TL;DR: Guard element instanceof Element and pass a single non-empty class token to element.classList.contains(className)—never use el.className.includes(...) for substring checks.
