In jQuery if you want to find out whether an element or elements are assigned a particular CSS Class then use .hasClass() method. It returns true when it finds the CSS class else returns false.
Syntax of jQuery hasClass
1
| $(selector).hasClass("classname"); |
The selector can either be an element or group of elements.
If the selector is a group of elements, then the jQuery hasClass will return true, if it finds the class assigned to any one of the elements.
If it does not find the class assigned to anyone, it returns false.
Example 1: Check if the Paragraph element has a certain Class
Click Button
This is a Paragraph
Suppose I have a paragraph element and I want to check if it contains the class myClass.
On the button click event I can use the jQuery hasClass() method and show this in the alert message to the user.
On the button click event I can use the jQuery hasClass() method and show this in the alert message to the user.
1
2
| <p class="myClass">This is a Paragraph</p><button id="myButton">Check Presence of Class</button> |
1
2
3
| $("#myButton").click(function(){ alert($("p").hasClass("myClass"));});Try it Yourself » |
On clicking the button you will receive true in the alert box.
Example 2: Change Color of all Paragraphs that have a Certain Class
Click Button
This is First Paragraph
This is Second Paragraph
This is Third Paragraph
Let me show how to change the color to Red, of all the paragraphs, that have the class as myClass.
1
2
3
4
| <p class="someClass">This is First Paragraph</p><p class="myClass">This is Second Paragraph</p><p>This is Third Paragraph</p><button id="changeColorButton">Change Color of “myClass” paragraph</button> |
In the jQuery Code first I will loop through each p elements using jQuery each. Then check if they have myClass or not.
If it is true I am applying the Red color to them with jQuery CSS method.
1
2
3
4
5
6
7
| $("#changeColorButton").click(function (e) { $("p").each(function (index, value) { var isClassPresent = $(this).hasClass("myClass"); if (isClassPresent) $(this).css("color", "Red"); });}); |
On clicking the button the second paragraph color will be changed to red.

