Check if an HTML element has a particular class in jQuery

It may be needed often to check if an HTML element has a particular class or not. Depending upon this fact you may need to perform some tasks. We can do it using the jQuery JavaScript library.

Here in this tutorial, we are now going to test if an element contains the specified 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 is assigned to the element and returns 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 uses the hasClass() method. Using an if...else statement we are checking if our element contains the class or not. Here we have selected the <p> tag or paragraph tag and testing if it contains the specific class name.

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 has the specific class assigned or not using jQuery and also get the idea of using jQuery hasClass() method.

Also read:

Leave a Reply

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