Check if an HTML element has a particular class in jQuery

By Faruque Ahamed Mollick

It may be needed often to check if an HTML element has a particular class or not and depending upon that perform the task. We can do it easily using jQuery. Here we are now going to test if an element contains the class or not in jQuery.

The jQuery .hasClass() method checks if a selected element contains a specified class name or not. The hasClass() method returns true if the class assigned to the element and return false if the class name is not assigned to that element.

Now see the jQuery code below:

if ($("p").hasClass('myClass')) {
	alert('Element contains the class');
} else {
	alert('Element does not contain the class');
}

The above jQuery code using the hasClass() method. In if else statement we are checking if our element contains the class or not. Here we have select the <p> tag or paragraph tag and testing if it contains the specific class name.

Calculate the distance between mouse and element in jQuery

How to set a timer in jQuery?

If the paragraph has the class name, the hasClass() method will return true and it will show the alert message “Element contains the class“, otherwise it will alert the other message “Element does not contain the class“.



So in this short tutorial post, we have just learned how to check an element if it the specific class is assigned or not using jQuery and also get the idea of using jQuery hasClass() method.

Leave a Reply

Your email address will not be published. Required fields are marked *