Question

Check Whether an Element Has a Class in JavaScript

cssjavascripthtmldom

Question

Using plain JavaScript, how can you check whether an element has a particular CSS class?

The following code compares the element's complete className string with one class name:

const test = document.getElementById("test");
const 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 = "";
}

It works for this element:

<div id="test" class="class1"></div>

However, when the element has multiple classes, the comparison no longer matches exactly:

<div id="test" class="class1 class5"></div>

How can the code detect class1 even when the element also has other classes?

Short Answer

You will learn why comparing className with === fails for elements with multiple classes, and how to use element.classList.contains() to test for one exact class safely. You will also see how to choose behavior when an element has more than one relevant class.

Concept

An HTML element can have zero, one, or many CSS classes in its class attribute:

<div class="card featured rounded"></div>

The className property represents the complete class attribute as a string. For the element above, it is typically:

"card featured rounded"

Therefore, this check asks whether the entire string is exactly "card":

element.className === "card"

It returns false when other classes are present.

Use classList when working with individual classes. classList is a collection-like API that treats each class as a separate token. Its contains() method checks whether one exact class is present:

element.classList.contains("featured"); // true

This matters because classes often describe several independent properties at once: layout, visual state, component type, accessibility state, or JavaScript behavior. A button might be both button, primary, and is-loading. Checking one class should not break merely because another class is added.

Mental Model

Think of an element's classes as labels attached to a storage box.

  • className is like reading the full line of labels at once: "fragile blue large".
  • Comparing className === "fragile" only succeeds if that is the only label.
  • classList.contains("fragile") is like looking through the labels and asking, “Is there a label named fragile?”

Classes are separate labels, not one single category.

Take Quiz

Syntax and Examples

The standard syntax is:

element.classList.contains("class-name");

It returns a Boolean:

  • true if the element has that class
  • false if it does not
<div id="test" class="class1 class5"></div>
const test = document.getElementById("test");

if (test.classList.contains("class1")) {
  test.textContent = "I have class1";
} else {
  test.textContent = "I do not have class1";
}

The result is I have class1 because class1 is one of the element's classes, even though class5 is also present.

For the original set of cases, check each class individually:

const 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 = "";
}

textContent is used here because the output is plain text. It avoids parsing the assigned value as HTML.

Step by Step Execution

Consider this code:

<div id="test" class="class1 class5"></div>
const test = document.getElementById("test");

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

Execution steps:

  1. document.getElementById("test") finds the <div> and stores it in test.
  2. test.classList accesses its individual class tokens: class1 and class5.
  3. contains("class1") searches those tokens for an exact match.
  4. It finds class1, so it returns true.
  5. The if block runs and sets the element text to I have class1.

If the HTML were <div id="test" class="class5"></div>, contains("class1") would return false, and the block would not run.

Real World Use Cases

Checking classes is common when JavaScript needs to respond to an element's current state or role.

  • Dropdown menus: Check is-open before closing or opening a menu.
  • Form validation: Check is-invalid to decide whether to show an error message.
  • Modal dialogs: Check is-visible before moving keyboard focus into a dialog.
  • Interactive lists: Check selected when a user chooses an item.
  • Event delegation: Check whether a clicked element has a behavior class such as delete-button.
  • Feature flags in markup: Check classes such as requires-confirmation before performing an action.

Example with a menu:

const menu = document.querySelector(".menu");

if (menu.classList.contains("is-open")) {
  menu.classList.remove("is-open");
} else {
  menu.classList.add("is-open");
}
Take Quiz

Real Codebase Usage

In real projects, classes often represent UI state. Developers commonly use classList.contains() together with add, remove, and toggle.

Guard clause

A guard clause exits early when the required class is absent:

function closeModal(modal) {
  if (!modal.classList.contains("is-open")) {
    return;
  }

  modal.classList.remove("is-open");
}

Event delegation

One listener can handle clicks from many dynamically created buttons:

document.addEventListener("click", (event) => {
  if (!event.target.classList.contains("delete-button")) {
    return;
  }

  console.log("Delete action requested");
});

Checking multiple required classes

Use every() when all classes must be present:

const requiredClasses = ["button", "primary", "is-enabled"];
const canSubmit = requiredClasses.every((name) =>
  submitButton.classList.contains(name)
);

Checking any matching class

Use some() when one of several classes is enough:

const statusClasses = ["success", "warning", "error"];
const hasStatus = statusClasses.some((name) =>
  message.classList.contains(name)
);

Choose class names that describe a stable purpose or state, such as is-open, is-loading, or has-error, rather than styling details such as red-text when possible.

Common Mistakes

Comparing the entire className string

This breaks as soon as another class is added or class order changes:

// Fragile: false for class="class1 class5"
test.className === "class1";

Use:

test.classList.contains("class1");

Using includes() on className

This can accidentally match part of a longer class name:

const element = document.querySelector(".button-primary");

// Incorrect: true, but "button" is not a class token here.
element.className.includes("button");

Use classList.contains("button"), which matches only complete class names.

Including the dot from a CSS selector

The dot belongs in CSS selector syntax, not in classList.contains():

// Incorrect
test.classList.contains(".class1");

// Correct
test.classList.contains("class1");

Forgetting that an element can have multiple matching classes

With if ... else if, only the first matching branch runs:

if (test.classList.contains("class1")) {
  // This runs first.
} else if (test.classList.contains("class5")) {
  // This will not run when both classes exist.
}

Use separate if statements if every matching action must run.

Accessing a missing element

If no element has the requested ID, getElementById() returns null:

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

if (test && test.classList.contains("class1")) {
  test.textContent = "I have class1";
}

Also ensure the script runs after the element exists, such as by placing the script at the end of <body> or waiting for DOMContentLoaded.

Comparisons

ApproachWhat it checksSuitable for class membership?Notes
element.classList.contains("active")One exact class tokenYesPreferred modern API.
element.className === "active"The entire class stringNoOnly works if it is the sole class in the same order.
element.className.includes("active")A text fragmentNoCan match inactive or another longer class name.
element.matches(".active")Whether the element matches a CSS selectorYesUseful when checking more than a class, such as .card.active.
element.classList.toggle("active")Adds or removes a classNot a check aloneReturns whether the class is present after toggling.

Use matches() when the condition is naturally a CSS selector:

if (element.matches("button.primary:not([disabled])")) {
  console.log("Enabled primary button");
}

Use classList.contains() when you only need to test one known class name.

Take Quiz

Cheat Sheet

// Check for one class
const hasActiveClass = element.classList.contains("active");

// Add a class
element.classList.add("active");

// Remove a class
element.classList.remove("active");

// Toggle a class; returns true if it is present afterward
const isActive = element.classList.toggle("active");

// Force a class to be present or absent
element.classList.toggle("active", shouldBeActive);

// Check all required classes
const hasAll = ["card", "featured"].every((className) =>
  element.classList.contains(className)
);

// Check whether any candidate class exists
const hasAny = ["success", "error"].some((className) =>
  element.classList.contains(className)
);

Rules:

  • Pass class names without a leading ..
  • contains() performs an exact class-token match.
  • Do not compare className for equality when multiple classes are possible.
  • Prefer textContent over innerHTML when inserting plain text.

FAQ

How do I check whether a div has a class in JavaScript?

Select the element and call classList.contains():

document.getElementById("test").classList.contains("class1");

Does classList.contains() work when an element has multiple classes?

Yes. It checks one class independently of every other class, so it works for class="class1 class5".

Should I include . in classList.contains(".active")?

No. Write classList.contains("active"). The period is only used in CSS selectors, such as document.querySelector(".active").

Why does element.className === "class1" fail?

className is the full class string. If the element has class="class1 class5", the value is not exactly "class1".

Can I use className.includes("class1") instead?

Avoid it. It can match part of another class name, such as my-class1-style. classList.contains("class1") checks exact class names.

How do I check for more than one class?

For all required classes, use every() with classList.contains(). For any matching class, use some().

What if getElementById() returns null?

The element does not exist yet or the ID is incorrect. Check for null, and make sure your script runs after the HTML element has been parsed.

Take Quiz

Mini Project

Description

Build a status message controller for a small interface. An element can have a base class plus one status class such as is-success, is-warning, or is-error. The script must identify the status without being affected by unrelated classes like rounded or shadow.

Goal

Display the correct status message by checking individual classes with classList.contains().

Requirements

Use an element that has multiple CSS classes. Check for is-success, is-warning, and is-error as exact class names. Show a different message for each recognized status. Show a fallback message when no recognized status class is present. Use textContent to insert the message.

Take Quiz

Keep learning

Related questions

View more