| by Arround The Web | No comments

What is the “hasClass” Function With Plain JavaScript

hasClass” method is the jQuery function used to verify whether the particular element contains the specified class. If it contains, the “hasClass()” gives “true” else, it returns “false”. jQuery is a library supported by JavaScript, if you want to do this task in JavaScript without using the jQuery library, use the “contains()” method.

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.


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:



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:

<div id = "logoDiv" class="flex-item1">

<img src="https://linuxhint.com/wp-content/uploads/2019/11/Logo-final.png" alt=""/>


Create a CSS class “flex-item1” to style the div:

.flex-item1 {

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:

let divElement = document.getElementById("logoDiv");

Call the “contains()” method of the classList object by passing the class “flex-item1” to determine whether the specified div element contains this class:

var hasclass = divElement.classList.contains("flex-item1");

Finally, print the result on the console using the “console.log()” method:

console.log("div contains class 'divElement'? "+ hasclass);

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.


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.

Share Button

Source: linuxhint.com

Leave a Reply