Check If an Element contains a Class

To check if an element contains a class, you use the contains() method of the classList property of the element:

element.classList.contains(className);Code language: CSS (css)

In this method, you pass the className to the contains() method of the classList property of the element. If the element contains the className, the method returns true. Otherwise, it returns false.

For example, suppose you have the following <div> element with two classes: secondary and info:

<div class="secondary info">Item</div>Code language: HTML, XML (xml)

To check if the <div> element contains the secondary class, you use the following code:

const div = document.querySelector('div');
div.classList.contains('secondary'); // trueCode language: JavaScript (javascript)

In this example, we use the querySelector() method to select the div and use the contains() method to check if its class list contains the secondary class.

The following example returns false because the <div> element doesn’t have the error class:

const div = document.querySelector('div');
div.classList.contains('error'); // falseCode language: JavaScript (javascript)

Summary

  • Use the element.classList.contains() method to check if an element contains a specific class name.
Was this tutorial helpful ?