jQuery > Attribute related method

hasClass (check for class attribute) in jQuery

How to check if an element has specific css class using jQuery?


To determine if a given css class name has been used for an element, hasClass() method can be used. 

 <div id="div1" class="class1">This is DIV1 with CLASS1</div>
 <div id="div2" class="class2">This is DIV2 with CLASS2</div>
 <div id="div3" class="class4">This is DIV3 with CLASS3</div>

<p><button onclick="GetStatus()">Check for class 'class3'</button> </p>

<script>
    alert($("#div2").hasClass('class2'));
    function GetStatus()
    {
        if ($("#div3").hasClass('class3')){
            alert('Yes');
        }
        else
        {
            alert('No');
        }
    }
</script>

Above code snippet will show alert as "true" if element whose id is “div2” will have class attribute value set as “class2” otherwise it will show alert as "false". 

In another example, on click of button, we are checking if 3rd div has class attribute set as 'class3' or not. In this case, clicking on button shows "No" as alert.

 Views: 1489 | Post Order: 28



Write for us