Question
Using plain JavaScript, not jQuery, how can you check whether an element has a specific CSS class?
For example, consider this code:
var test = document.getElementById("test");
var testClass = test.className;
switch (testClass) {
case "class1":
test.innerHTML = "I have class1";
break;
case "class2":
test.innerHTML = "I have class2";
break;
case "class3":
test.innerHTML = "I have class3";
break;
case "class4":
test.innerHTML = "I have class4";
break;
default:
test.innerHTML = "";
}
<div id="test" class="class1"></div>
This works when the element has exactly one class. However, if the HTML changes to:
<div id="test" class="class1 class5"></div>
there is no exact string match anymore, even though the element still includes class1. How can you correctly detect whether the element contains a particular class, even when it has multiple classes?
Short Answer
By the end of this page, you will understand how JavaScript stores classes on DOM elements, why comparing the full className string often fails, and how to correctly check for a single class using classList.contains(). You will also see fallback ideas, common mistakes, and practical examples used in real projects.
Concept
In JavaScript, an HTML element can have multiple CSS classes at the same time.
For example:
<div class="class1 class5"></div>
This element has two classes:
class1class5
When you read element.className, JavaScript gives you the entire class string, not one class at a time.
console.log(element.className); // "class1 class5"
That means a switch statement or direct equality check like this:
if (element.className === "class1")
only works when the class attribute is exactly "class1". It fails if there are extra classes, a different order, or extra spaces.
The correct modern solution is to use the DOM classList API:
Mental Model
Think of an element's classes like stickers placed on a box.
A box might have these stickers:
fragilebluepriority
If you ask, "Is this box exactly fragile?" the answer is no, because it has more than one sticker.
But if you ask, "Does this box have the fragile sticker?" the answer is yes.
That is the difference between:
- checking the full
classNamestring - checking whether one class exists inside the class list
classList.contains("class1") is the JavaScript way of asking, "Does this box have this sticker?"
Syntax and Examples
The modern syntax is:
element.classList.contains("className")
It returns:
trueif the class existsfalseif it does not
Basic example
<div id="test" class="class1 class5"></div>
var test = document.getElementById("test");
if (test.classList.contains("class1")) {
test.textContent = "I have class1";
} else {
test.textContent = "";
}
In this example:
- the element has both
class1andclass5
Step by Step Execution
Consider this code:
<div id="test" class="class1 class5"></div>
var test = document.getElementById("test");
if (test.classList.contains("class1")) {
test.textContent = "I have class1";
} else {
test.textContent = "";
}
Step by step
document.getElementById("test")finds the<div>element.- The variable
testnow refers to this element. test.classListgives access to the element's class list.test.classList.contains("class1")checks whetherclass1is one of the classes.- The element has
class="class1 class5", so the result is .
Real World Use Cases
Checking for classes is common in real front-end code.
Show or hide UI state
if (menu.classList.contains("open")) {
menu.classList.remove("open");
} else {
menu.classList.add("open");
}
Used in:
- dropdown menus
- modals
- sidebars
- accordions
Validate state before doing something
if (button.classList.contains("disabled")) {
return;
}
Used in:
- buttons
- forms
- loading states
Event delegation
document.addEventListener("click", function (event) {
if (event.target.classList.contains()) {
.();
}
});
Real Codebase Usage
In real projects, developers usually use class checks in small, readable patterns.
Guard clauses
A guard clause exits early if a class is present or missing.
if (!card.classList.contains("selected")) {
return;
}
console.log("Process selected card");
This avoids deep nesting.
State-driven UI
function toggleModal(modal) {
if (modal.classList.contains("open")) {
modal.classList.remove("open");
return;
}
modal.classList.add("open");
}
This is common for UI state management.
Validation before action
function submitForm(button) {
if (button.classList.()) {
;
}
button..();
}
Common Mistakes
1. Comparing the full className string
Broken example:
if (test.className === "class1") {
console.log("yes");
}
Why it fails:
- it only matches exact text
- it breaks when there are multiple classes
- it can break if class order changes
Better:
if (test.classList.contains("class1")) {
console.log("yes");
}
2. Using includes() directly on className
Broken example:
if (test.className.includes("class1")) {
console.log("yes");
}
Why it is risky:
This can produce false matches. For example, would also match .
Comparisons
| Approach | What it checks | Good for | Problems |
|---|---|---|---|
element.className === "class1" | Exact full class string | Rare cases with exactly one class | Fails with multiple classes or different order |
element.classList.contains("class1") | Whether one class exists | Most modern JavaScript code | Requires DOM classList support |
element.className.includes("class1") | Substring inside class string | Quick experiments only | False matches like class10 |
element.matches(".class1") | Whether the element matches a CSS selector | Useful with selectors |
Cheat Sheet
Quick syntax
element.classList.contains("my-class")
Returns true or false.
Useful classList methods
element.classList.add("my-class");
element.classList.remove("my-class");
element.classList.toggle("my-class");
element.classList.contains("my-class");
Best practice
Use this:
if (element.classList.contains("active")) {
// do something
}
Avoid this for class existence checks:
element.className === "active"
element.className.includes()
FAQ
How do I check if an element has a class in JavaScript?
Use element.classList.contains("class-name"). It returns true if the class exists.
Why does className === "class1" fail?
Because className returns the full class string. If the element has class="class1 class5", the string is not exactly "class1".
Can an HTML element have multiple classes?
Yes. Classes are separated by spaces inside the class attribute.
Is classList.contains() better than checking className manually?
Yes. It is clearer, safer, and correctly handles multiple classes.
Can I use includes() on className?
You can, but it is not recommended because it may match partial names such as class1 inside class10.
What is the difference between classList.contains() and matches()?
Mini Project
Description
Build a small status message component that reads an element's classes and displays a message based on which known class is present. This demonstrates how to check for classes safely when elements may have more than one class.
Goal
Create a script that detects specific classes on an element and shows the correct message even when multiple classes are present.
Requirements
- Select an element from the page using JavaScript.
- Check whether it contains
class1,class2,class3, orclass4. - Display the first matching message inside the element.
- Make sure the code still works if the element has additional classes.
- Use plain JavaScript only.
Keep learning
Related questions
Allow Only Numeric Input (0-9) in HTML Input Using jQuery
Learn how to allow only digits 0-9 in an HTML input using jQuery, with examples, validation tips, common mistakes, and best practices.
CSS :not() Selector for Excluding a Class or Attribute
Learn how to use the CSS :not() selector to target elements that do not have a specific class or attribute, with examples and common mistakes.
Can HTML Checkboxes Be Readonly? Understanding readonly vs disabled in HTML Forms
Learn why HTML checkboxes do not support readonly, how disabled differs, and practical ways to prevent changes while still submitting values.