How to check if an element contains a class in JavaScript?

To check if an element contains a specific class in JavaScript, you can use the classList property (modern approach) or the className property (legacy approach). Below is a detailed explanation with examples for both methods.

1. Using classList.contains() (Modern Method)

The classList property returns a live DOMTokenList of the element’s classes. It provides the contains() method to check if a class exists.

Syntax:

element.classList.contains('className');

Example:

<div id="myElement" class="container active">Example Element</div>
const element = document.getElementById('myElement');

// Check if the element has the class "active"
if (element.classList.contains('active')) {
  console.log('Element has the class "active"');
} else {
  console.log('Element does NOT have the class "active"');
}

Output:

Element has the class "active"

Key Points:

  • Case Sensitivity: Class names are case-sensitive (e.g., Activeactive).
  • Multiple Classes: Works seamlessly with elements that have multiple classes.
  • Browser Support: Supported in all modern browsers (IE10+).

2. Using className (Legacy Method)

The className property returns a string of the element’s classes. You can split this string into an array and check for the class.

Syntax:

element.className.split(' ').includes('className');

Example:

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

// Split the className string into an array and check inclusion
const classes = element.className.split(' ');
if (classes.includes('active')) {
  console.log('Element has the class "active"');
}

Output:

Element has the class "active"

Edge Cases to Handle:

  • Extra Spaces: Use trim() to remove leading/trailing spaces.
  • Multiple Spaces: Split using a regular expression to handle multiple spaces.

Improved Code:

const classes = element.className.trim().split(/\s+/);
if (classes.includes('active')) {
  // Class exists
}

3. Helper Function for className

For reusability, create a helper function to check class existence using className:

function hasClass(element, className) {
  return element.className
    .trim() // Remove leading/trailing spaces
    .split(/\s+/) // Split by one or more spaces
    .includes(className);
}

// Usage
if (hasClass(element, 'active')) {
  console.log('Class found!');
}

4. Example Use Cases

Case 1: Toggle a Class Based on Presence

const button = document.querySelector('button');

if (button.classList.contains('disabled')) {
  button.classList.remove('disabled');
} else {
  button.classList.add('disabled');
}

Case 2: Check Class in Event Listeners

document.querySelector('.menu-item').addEventListener('click', function(e) {
  if (e.target.classList.contains('active')) {
    e.target.classList.remove('active');
  } else {
    e.target.classList.add('active');
  }
});

Comparison of Methods

MethodProsCons
classList.containsClean, efficient, handles edge casesNot supported in IE9 and earlier
classNameWorks in all browsersRequires manual handling of spaces

Browser Compatibility

  • classList: Supported in IE10+, Chrome 8+, Firefox 3.6+, Safari 5.1+.
  • className: Works in all browsers.

Best Practices

  1. Use classList.contains() for modern applications.
  2. Fallback for Legacy Browsers: Use the className approach if supporting IE9 or older.
  3. Trim and Split: Always sanitize the className string to avoid false negatives.

Summary

  • Modern Approach:
  element.classList.contains('className');
  • Legacy Approach:
  element.className.trim().split(/\s+/).includes('className');

By using these methods, you can reliably check for class existence in JavaScript.

Leave a Reply

Your email address will not be published. Required fields are marked *