Checking for CSS Classes with JavaScript

Checking for CSS Classes with JavaScript

Often in web development, you need to determine if an HTML element has a specific CSS class. This allows you to dynamically change the behavior or appearance of an element based on its assigned classes. While libraries like jQuery provide convenient methods for this, it’s crucial to understand how to accomplish this with vanilla JavaScript. This tutorial will cover several approaches to check if an element possesses a particular CSS class.

The classList API: The Modern Approach

The most modern and recommended approach is to utilize the classList API, available on most modern browsers. The classList property provides a convenient interface for manipulating an element’s class attributes.

The contains() method of the classList API is specifically designed to check if an element has a given class.

Here’s how it works:

const element = document.body; // Or any other element
const className = 'thatClass';

if (element.classList.contains(className)) {
  // The element has the class 'thatClass'
  console.log('Element has the class:', className);
  // Perform actions based on the presence of the class
} else {
  // The element does not have the class 'thatClass'
  console.log('Element does not have the class:', className);
}

This method is clean, readable, and efficient.

Browser Support:

The classList API has excellent browser support:

  • Chrome 8.0+
  • Firefox 3.6+
  • IE 10+
  • Opera 11.50+
  • Safari 5.1+

For older browsers, you’ll need to use alternative methods.

Other classList methods:

The classList API provides other useful methods:

  • add(className): Adds a class to the element.
  • remove(className): Removes a class from the element.
  • toggle(className): Adds the class if it’s absent, and removes it if it’s present.
  • replace(oldClass, newClass): Replaces an existing class with a new one.

Using className and Regular Expressions (For Wider Compatibility)

If you need to support older browsers that don’t support the classList API, you can use the className property in conjunction with regular expressions.

const element = document.body;
const className = 'thatClass';
const regex = new RegExp('\\b' + className + '\\b'); // Add word boundaries for accuracy

if (regex.test(element.className)) {
  // The element has the class 'thatClass'
  console.log('Element has the class:', className);
} else {
  // The element does not have the class 'thatClass'
  console.log('Element does not have the class:', className);
}

Explanation:

  1. We access the className property of the element, which returns a string containing all the element’s classes.
  2. We create a regular expression using the RegExp constructor. The \b ensures that we’re matching whole words (class names). Without this, searching for ‘thisClass’ could incorrectly return a positive result if the element has the class ‘thisClass-suffix’.
  3. We use the test() method of the regular expression to check if the className string contains the target class name.

This approach is more verbose than using the classList API, but it offers broader compatibility with older browsers, including those predating the classList specification.

Considerations and Best Practices

  • Performance: For modern browsers, the classList API is generally more performant than using regular expressions on the className string.
  • Specificity: Always be mindful of CSS specificity when manipulating classes dynamically. Ensure that your changes don’t inadvertently override other styles.
  • Multiple Classes: The techniques discussed here can easily be adapted to check for multiple classes. You can combine multiple regular expressions or use multiple classList.contains() calls.
  • Avoid jQuery Dependency: While jQuery provides a convenient hasClass() method, it’s best to avoid unnecessary dependencies on external libraries when vanilla JavaScript can achieve the same result.

Leave a Reply

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