jQuery hasClass() Method

jQuery hasClass() Method

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.

Syntax of jQuery hasClass

$(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.

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 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.

Related to jQuery hasClass Methods

Example 2: Change Color of all Paragraphs that contains the 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 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> 
In the jQuery Code first I will loop through each p elements using jQuery each method. Inside the .each() method I check if they have myClass or not.

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:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate