In jQuery, if you want to find out whether some elements (or a single element) are assigned a particular CSS Class then use the .hasClass() method. It returns true when it finds the CSS class else returns false.
$(selector).hasClass("classname");
The selector can either be an element or a group of elements.
Note: If the selector is a group of elements – in this case 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 then it returns false.
This is a Paragraph
Suppose I have a paragraph element and I want to check if it contains the class called myClass. Here, on the button click event I can use the jQuery hasClass() method and show the result in the alert message to the user.
<p class="myClass">This is a Paragraph</p>
<button id="myButton">Check Presence of Class</button>
$("#myButton").click(function(){
alert($("p").hasClass("myClass"));
});
On clicking the button you will receive true on the alert box.
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 called myClass.
<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>
So if the .hasClass() method returns true then I apply the Red color to the paragraph elements. I used jQuery CSS method to apply the red color.
$("#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.
Kindly check the important link given below: