jQuery hasClass() Method

jQuery hasClass() Method

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 if it finds the class else returns false.

Syntax of jQuery hasClass

$(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 whose name is myClass.
On the button click event I can use the jQuery hasClass() method and show this 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"));
});Try it Yourself »

On clicking the button you will receive true in the alert box.
Test Code

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

<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 using jQuery CSS method.

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

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.