jQuery hasClass() Attribute

jQuery hasclass() attribute checks the value of the class attribute for a specified class. This method returns boolean value, either TRUE or FALSE.

Syntax of hasClass() attribute

$(selector).hasclass(classname) 

The selector is the element on which hasClass attribute checks the given 'classname'. The 'classname' is the required field. It is the name of class.

Example

<p class="cls" id="demo"> Hello World!</p>
<button id="btn">Click Here</button>

<script>
$(document).ready(function(){
$("button#btn").click(function(){
alert( $("p#demo").hasClass("cls"));
});
});
</script>

Output of the above code

Hello World!


In the above example, hasClass attribute checks the existence of 'cls' class in the paragraph of id 'demo'.


Example

<style>
.cls1 { 
font-size: 22px;
}
.cls2 { 
font-style: italic; 
color: green;
}
</style>

<p class="cls1" id="demo1"> Hello World!</p>

<script>
$(document).ready(function(){
if($("p#demo1").hasClass("cls1")) {
$("p#demo1").addClass("cls2");
}
});
</script>

Output of the above code

Hello World!

In the above example, hasClass attribute checks the existence of 'cls1' class in the paragraph of id 'demo1'. If it exists, then adds 'cls2' class to the paragraph. Here, hasClass acts as a boolean expression.




Read more articles


General Knowledge



Learn Popular Language