This article will demonstrate the “hasClass” function with plain JavaScript.
How to Perform the Functionality of “hasClass” Function With Plain JavaScript?
“hasClass” function belongs to the JavaScript “jQuery” library. If you want to use plain JavaScript and identify whether the specified class is a part of a particular element, then you have to use the “contains()” method of the classList object. This works the same as the hasClass function.
Syntax
To get the functionality of “hasClass” in JavaScript, use the below-given syntax:
Here, “className” is the name of the CSS class that will be searched in the particular element.
While the syntax of the hasClass() method in jQuery is:
Example
Create a “div” element, assign a CSS class “flex-item1” to style the div, and add an image of the logo of the website using the “src” attribute of the <img> tag inside the div element:
<img src="https://linuxhint.com/wp-content/uploads/2019/11/Logo-final.png" alt=""/>
</div>
Create a CSS class “flex-item1” to style the div:
background-color: black;
max-width: 7em;
display: flex;
align-items: center;
padding: 0 15px;
}
In JavaScript file, or the <script> tag, first get the element “div” using its assigned id “logoDiv” with the help of getElementById() method:
Call the “contains()” method of the classList object by passing the class “flex-item1” to determine whether the specified div element contains this class:
Finally, print the result on the console using the “console.log()” method:
It can be observed that the contains() method returned “true” which means the specified element contains the given CSS class:
We have compiled the necessary instructions relevant to performing the “hasClass” functionality with plain JavaScript.
Conclusion
In JavaScript, you can achieve the functionality of the “hasClass” function using the “contains()” method of the classList object. The “hasClass()” is the built-in method of the JavaScript “jQuery” library. It is utilized to check or verify whether the particular element belongs to the specified class. In this article, we demonstrated the hasClass function and the equivalent method in plain JavaScript.