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: 8359 | Post Order: 28