To check if an element contains a class or not, you can use the contains()
method of the classList
property of the element.
Here is the syntax of the contains()
method:
element.classList.contains(className);
The contains()
method takes a single parameter className
which is the name of the class which we want to check. If the element already has the specified class, the contains() method returns true. Otherwise, it returns false.
Let’s say we have a div element in our HTML file which have two classes warning
and info
:
<div class="warning info">This is a div element</div>
Now, we want to dynamically check if the div element contains the class warning
or not with the help of JavaScript.
To do that, we will first get the element with any DOM selector method such as getElementById()
or querySelector()
etc. After that, we can use the contains()
method to check if the class exists or not.
The following code shows how you can do it:
// Get the element const div = document.querySelector('div'); console.log(div.classList.contains('warning')); // true console.log(div.classList.contains('error')); // false
In the above example, the contains()
method first checks if the warning
class exists on the div element or not. Because it is already there, therefore, it returns true.
In the second case, it returns false because the error
class does not exist on the div element.
Summary
In this article, we have learned how we can check if a given class exists on an element or not. We used the element.classList.contains(className)
method, which returns true if the given class already exists, otherwise, it returns false.