Question

How to Check Whether an Element Has a Class in JavaScript

htmljavascriptcssdom

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:

  • class1
  • class5

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:

element.classList.contains("class1")

This checks whether the element has that specific class, regardless of what other classes are also present.

This matters because real applications almost always combine multiple classes for:

  • styling
  • state changes
  • JavaScript behavior
  • responsive layouts
  • feature flags

So instead of treating the class attribute as one exact string, you should think of it as a list of class names.

Mental Model

Think of an element's classes like stickers placed on a box.

A box might have these stickers:

  • fragile
  • blue
  • priority

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 className string
  • checking whether one class exists inside the class list

classList.contains("class1") is the JavaScript way of asking, "Does this box have this sticker?"

Take Quiz

Syntax and Examples

The modern syntax is:

element.classList.contains("className")

It returns:

  • true if the class exists
  • false if 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 class1 and class5
  • classList.contains("class1") returns true
  • the text becomes I have class1

Checking multiple possible classes

var test = document.getElementById("test");

if (test.classList.contains("class1")) {
  test.textContent = "I have class1";
} else if (test.classList.contains("class2")) {
  test.textContent = "I have class2";
} else if (test.classList.contains("class3")) {
  test.textContent = "I have class3";
} else if (test.classList.contains("class4")) {
  test.textContent = "I have class4";
} else {
  test.textContent = "";
}

This is a better replacement for the original switch because each condition checks for one class independently.

Older string-based approach

If you cannot use classList, you may see older code like this:

if (test.className.split(" ").includes("class1")) {
  test.textContent = "I have class1";
}

This works in simple cases, but classList.contains() is cleaner and more reliable.

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

  1. document.getElementById("test") finds the <div> element.
  2. The variable test now refers to this element.
  3. test.classList gives access to the element's class list.
  4. test.classList.contains("class1") checks whether class1 is one of the classes.
  5. The element has class="class1 class5", so the result is true.
  6. The if block runs.
  7. test.textContent = "I have class1" sets the visible text inside the <div>.

Trace of values

test.className           // "class1 class5"
test.classList.contains("class1") // true
test.classList.contains("class5") // true
test.classList.contains("class2") // false

The important point is that JavaScript checks for a single class inside the list, not equality against the full string.

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("delete-button")) {
    console.log("Delete clicked");
  }
});

Used in:

  • lists of items
  • dynamically created elements
  • tables
  • reusable components

Styling plus behavior

Classes often represent both look and meaning:

  • active
  • hidden
  • selected
  • error
  • loading

JavaScript checks these classes to decide what should happen next.

Take Quiz

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.contains("loading")) {
    return;
  }

  button.classList.add("loading");
}

This prevents duplicate actions.

Working with groups of elements

var items = document.querySelectorAll(".menu-item");

items.forEach(function (item) {
  if (item.classList.contains("active")) {
    console.log("Active item:", item.textContent);
  }
});

Combining with matches() when needed

Sometimes developers use matches() for selector-based checks:

if (element.matches(".class1")) {
  console.log("Has class1");
}

This is useful when checking more than just a class, such as:

element.matches("button.primary")

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, class1 would also match class10.

Better:

if (test.classList.contains("class1")) {
  console.log("yes");
}

3. Forgetting that classes are case-sensitive

test.classList.contains("Class1"); // false if actual class is "class1"

Use the exact class name.

4. Using innerHTML when plain text is enough

If you only want to set text, prefer textContent:

test.textContent = "I have class1";

This is simpler and safer.

5. Assuming one element always exists

Broken example:

var test = document.getElementById("missing");
if (test.classList.contains("class1")) {
  console.log("yes");
}

This throws an error because test is null.

Better:

var test = document.getElementById("missing");

if (test && test.classList.contains("class1")) {
  console.log("yes");
}

Comparisons

ApproachWhat it checksGood forProblems
element.className === "class1"Exact full class stringRare cases with exactly one classFails with multiple classes or different order
element.classList.contains("class1")Whether one class existsMost modern JavaScript codeRequires DOM classList support
element.className.includes("class1")Substring inside class stringQuick experiments onlyFalse matches like class10
element.matches(".class1")Whether the element matches a CSS selectorUseful with selectorsSlightly broader than a simple class check

classList.contains() vs matches()

element.classList.contains("active");
element.matches(".active");

Both can work for a class check.

Use classList.contains() when:

  • you only care about one class
  • you want the clearest intent

Use matches() when:

  • you want selector logic
  • you need checks like button.primary or .card.active

switch vs if / else if

A switch works well for one exact value:

switch (status) {
  case "loading":
    break;
}

But class checking is usually better with if / else if, because an element may have many classes at once.

if (el.classList.contains("class1")) {
  // ...
} else if (el.classList.contains("class2")) {
  // ...
}
Take Quiz

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("active")

Safe element check

if (element && element.classList.contains("active")) {
  // safe
}

Multiple class checks

if (el.classList.contains("error")) {
  // ...
} else if (el.classList.contains("success")) {
  // ...
}

Selector alternative

element.matches(".active")

Edge cases

  • Class names are case-sensitive.
  • Elements can have multiple classes.
  • Class order does not matter with classList.contains().
  • Extra spaces in className string are another reason not to rely on exact string equality.

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()?

classList.contains() checks one class name. matches() checks whether the element satisfies a CSS selector.

Should I use innerHTML or textContent here?

Use textContent if you are only setting text. Use innerHTML only when you intentionally want to insert HTML.

Take Quiz

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, or class4.
  • Display the first matching message inside the element.
  • Make sure the code still works if the element has additional classes.
  • Use plain JavaScript only.
Take Quiz

Keep learning

Related questions

View more