Checking if an Element Has a Given Class in JavaScript

Checking whether an element has a particular class is a common operation in JavaScript, especially when working with dynamic user interfaces and applying styles conditionally.

In this article, we'll explore different methods to check if an element has a given class using plain JavaScript.

Method 1: Using the "classList" Property

The classList property provides methods to manipulate classes on an element, including checking if it contains a specific class.

// Get the element by its ID
const myElement = document.getElementById('myElement');

// Check if the element has the class 'myClass'
const hasClass = myElement.classList.contains('myClass');

// Log the result to the console
console.log(hasClass);

In this example, replace 'myElement' with the actual ID or reference to the element you want to check, and 'myClass' with the class you are checking for.

The contains method returns true if the class is present and false otherwise.

Method 2: Using the "className" Property

The className property contains a space-separated string representing the classes of an element. You can use this property to check if a specific class is present.

// Get the element by its ID
const myElement = document.getElementById('myElement');

// Check if the element has the class 'myClass'
const hasClass = myElement.className.includes('myClass');

// Log the result to the console
console.log(hasClass);

This method uses the includes method to check if the class name string contains the desired class.

Method 3: Using the indexOf Method

Another way to check if an element has a given class is by using the indexOf method.

// Get the element by its ID
const myElement = document.getElementById('myElement');

// Check if the element has the class 'myClass'
const hasClass = myElement.className.indexOf('myClass') !== -1;

// Log the result to the console
console.log(hasClass);

The indexOf method returns the index of the first occurrence of a specified value in a string. If the class is not found, it returns -1.

Conclusion

Checking if an element has a given class is a routine task in JavaScript, especially in the context of DOM manipulation and user interface interactions.

Whether you use the classList property, className property with includes, or indexOf method, each method has its use cases and considerations.

Choose the approach that best fits your project's requirements and coding style, ensuring that you can efficiently and accurately determine the presence of a class on an element.