JavaScript
Web Development
Programming
Coding
HTML DOM

Check if an element contains a class in JavaScript?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The standard way to check whether a DOM element has a CSS class in modern JavaScript is element.classList.contains("className"). It is safer and clearer than manually parsing the className string because it works with actual class tokens rather than raw text fragments.

This matters because class names are a token list, not a free-form string. Once you treat them as tokens, false matches and fragile string parsing mostly disappear.

Use classList.contains()

Every modern browser exposes classList on ordinary DOM elements. The contains() method returns true only if the class exists as an actual token.

javascript
1const element = document.getElementById("myDiv");
2const hasActive = element.classList.contains("active");
3
4console.log(hasActive);

This is the recommended answer for almost all normal DOM code.

Why It Is Better Than className

Older code often manipulates element.className directly. That can work, but it is easier to get wrong.

Bad pattern:

javascript
const hasActive = element.className.indexOf("active") !== -1;

This can incorrectly match inactive, active-item, or other unintended substrings.

A token-aware API avoids that entire class of bug.

A slightly better fallback is splitting the string manually:

javascript
const hasActive = element.className.split(/\s+/).includes("active");

But classList.contains() is still clearer and less error-prone.

A Simple Real Example

html
<button id="saveButton" class="btn active">Save</button>
javascript
1const button = document.getElementById("saveButton");
2
3if (button.classList.contains("active")) {
4  console.log("Button is active");
5} else {
6  console.log("Button is not active");
7}

This is a common pattern in menus, tabs, validation states, and interactive components.

Be Careful with Event Targets

If you get the node from an event, make sure it is actually an element before reading classList.

javascript
1document.addEventListener("click", (event) => {
2  const target = event.target;
3
4  if (target instanceof Element && target.classList.contains("dismiss")) {
5    console.log("Dismiss element clicked");
6  }
7});

That extra check helps when event bubbling or complex DOM content makes the target less predictable than you expected.

Checking Many Elements

If you need to inspect several elements, query them first and then loop over them.

javascript
1const items = document.querySelectorAll(".menu-item");
2
3items.forEach((item) => {
4  if (item.classList.contains("selected")) {
5    console.log("Selected item:", item.textContent);
6  }
7});

Remember that a NodeList is a collection, not a single element. classList.contains() belongs on each element, not on the entire list.

classList Is Useful Beyond Checking

One reason classList is the right API is that it keeps the whole workflow consistent. The same interface lets you inspect and modify classes.

javascript
1if (!element.classList.contains("open")) {
2  element.classList.add("open");
3}
4
5element.classList.remove("hidden");
6element.classList.toggle("selected");

That is easier to maintain than mixing manual string inspection with token-based updates.

Older Environment Fallback

If you ever have to support very old browser environments where classList is not available, you can fall back to splitting className.

javascript
function hasClass(element, className) {
  return element.className.split(/\s+/).includes(className);
}

Treat that as a compatibility fallback, not the preferred modern solution.

Common Pitfalls

The biggest mistake is using substring matching on className, which can return false positives. Another is calling classList.contains() on something that is not actually a DOM element, such as an unexpected event target. Developers also often forget that querySelectorAll() returns a collection rather than one element. Finally, manual string parsing makes whitespace and token-boundary bugs much easier to introduce than simply using classList directly.

Summary

  • Use element.classList.contains("name") to check for a class.
  • It is more reliable than parsing className manually.
  • Avoid substring searches such as indexOf on the full class string.
  • Validate event targets when needed before reading classList.
  • Use the rest of the classList API for add, remove, and toggle operations too.

Course illustration
Course illustration

All Rights Reserved.