Javascript Check If Element Has Class

5 min read

Introduction

When working with the Document Object Model (DOM) in JavaScript, one of the most common tasks is determining whether a specific element already possesses a particular CSS class. The ability to check if an element has a class efficiently is essential for dynamic styling, event handling, and conditional logic in modern web applications. This article explores the built‑in JavaScript techniques for performing this check, explains the underlying concepts, and offers best‑practice guidance to help you write cleaner, faster, and more maintainable code.

Why Checking Element Classes Matters

CSS classes act as semantic markers that link visual styles to DOM elements. In a typical web page you might:

  • Apply a “active” class to navigation links based on the current page.
  • Toggle a “show” class to reveal hidden content panels.
  • Add a “error” class to form fields that fail validation.

To implement any of these interactions, you first need to know whether the class already exists before you decide to add, remove, or toggle it. This prevents unnecessary reflows, reduces redundant style calculations, and keeps your logic predictable.

Methods to Check for a Class in JavaScript

JavaScript provides several ways to inspect an element’s class list. Below are the most widely used approaches, each with its own strengths and typical use‑cases That alone is useful..

Using the className property

The className property returns the raw class attribute as a single string. While simple, it requires string manipulation to locate a specific class Most people skip this — try not to. Practical, not theoretical..

const element = document.getElementById('myDiv');

if (element.className.includes('active')) {
  // element has the 'active' class
}

Pros: Works in all browsers, no extra overhead.
Cons: Fails when class names contain spaces or hyphens; case‑sensitive; can be slower with many classes.

Using classList.contains()

The modern classList API introduces a dedicated method contains() that checks for the presence of a class in a more solid way.

const element = document.querySelector('.container');

if (element.classList.contains('highlight')) {
  // element is highlighted
}

Pros: Handles multiple spaces, ignores case‑sensitivity issues, and is highly readable.
Cons: Slightly more verbose than a simple string check.

Using classList with has() (ES2022)

ES2022 added classList.has(), which is essentially an alias for contains(). It is supported in all modern browsers.

if (element.classList.has('disabled')) {
  // element is disabled
}

Using querySelector with an attribute selector

When you need to verify a class and the element’s tag or other attributes, you can combine querySelector with an attribute selector. This method returns the element itself if it matches, otherwise null.

const element = document.querySelector('.wrapper.active');

if (element) {
  // element with both 'wrapper' and 'active' classes exists
}

Pros: Useful for complex selectors and when you need to locate the element in a single step.
Cons: Returns the first matching element only; may be less intuitive for simple checks Simple, but easy to overlook..

Using matches() for flexible checks

The matches() method determines whether an element would be selected by a CSS selector. It is handy when you want to test class presence alongside other criteria Not complicated — just consistent..

const element = document.getElementById('btn');

if (element.matches('.btn-primary:hover')) {
  // element is a button with the primary class and is being hovered
}

Using Array.prototype.some() on className split

If you prefer a functional approach, you can split the className string into an array and use some() to test each class.

const element = document.getElementById('box');
const classes = element.className.split(/\s+/);

const hasError = classes.some(cls => cls === 'error');

if (hasError) {
  // error styling needed
}

Pros: Works with older browsers, functional style.
Cons: Slightly more overhead due to array creation.

Best Practices

  1. Prefer classList.has() or classList.contains() – they are purpose‑built, readable, and handle edge cases like extra whitespace automatically.
  2. Cache references – repeatedly querying the DOM (document.getElementById) inside loops or event handlers can cause performance bottlenecks. Store the element in a variable.
  3. Use consistent naming – adopt a naming convention (e.g., kebab‑case or camelCase) for classes and reference them exactly as they appear in the HTML.
  4. Avoid string manipulation – className.includes is error‑prone; rely on the DOM API whenever possible.
  5. Consider performance for large lists – if you have many elements and need to check classes frequently, batch updates or use DocumentFragment to minimize reflows.

Common Pitfalls

  • Case sensitivity: CSS class names are case‑sensitive in HTML, so 'Active' is not the same as 'active'. Always match the exact casing.
  • Multiple spaces: The className property may contain consecutive spaces after class removal. Using classList sidesteps this issue.
  • SVG elements: In SVG, class checking works similarly, but be aware that classList is supported in modern browsers.
  • Dynamic class addition: If you add classes via classList.add while checking, ensure you are not reading stale data. Re‑query or use event listeners for immediate updates.

Performance Considerations

When checking classes for thousands of elements, the cost can add up:

  • Avoid document.querySelectorAll inside a loop – it will re‑traverse the DOM each iteration.
  • Use DocumentFragment for batch operations – build a fragment, apply class checks, then insert once.
  • apply requestAnimationFrame for visual updates that depend on class presence; this syncs changes with the browser’s paint cycle.

Benchmarking shows classList.has() is marginally faster than string‑based checks, especially when dealing with multiple classes The details matter here. Which is the point..

Real‑World Example: Toggle Navigation Menu

Below is a practical snippet that demonstrates checking for a class to toggle a responsive navigation menu. The code follows the best‑practice recommendations outlined above Most people skip this — try not to..

// Select the hamburger button and the navigation list
const navToggle = document.getElementById('nav-toggle');
const navList = document.querySelector('.nav-list');

 // Attach a click event listener
navToggle.addEventListener('click', () => {
  // Check if the nav list already has the 'show' class
  const isVisible = navList.classList.

  // Toggle visibility by adding or removing the class
  if (isVisible) {
    navList.That said, classList. So remove('show');
  } else {
    navList. classList.

**Explanation:**  
- `navList.classList.contains('show')` provides a clear, readable way to determine the current state.  
- By caching the element reference (`navList`), we avoid repeated DOM queries.  
- The logic is simple and maintainable, making it easy for other developers to understand.
Brand New Today

Recently Completed

Based on This

A Natural Next Step

Thank you for reading about Javascript Check If Element Has Class. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home