jQuery hasClass()
0 1242
- This jQuery method is used to check weather a class is attached to any of the selected HTML element or not.
- Return type of this method is Boolean means this method returns TRUE if any of the selected HTML element have the given class otherwise returns FALSE.
Related Topics:
jQuery position
jQuery addClass
jQuery hasClass
Syntax:
$(selector).hasClass(class_name);
Parameter description:
- class_name: This parameter represents the name of class or classes to be check to attach to any of the selected element. It is mandatory.
Example:
In this example we check the try class is attaching to any of the given heading or not.
<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
h3{
background:yellow;
padding:10px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$res=$("h3").hasClass("try");
if($res){
alert("one of the given heading has class try");
}else{
alert("No heading has class try");
}
});
;
});
</script>
</head>
<body>
<h2> jQuery hasClass() Method Example </h2>
<h3> This is heading 1 </h3>
<h3 class="try"> This is heading 2 </h3>
<h3> This is heading 3 </h3>
<h3> This is heading 4 </h3>
<button> Click me! </button>
</body>
</html>
Output:
When you click the button,
Share:
Comments
Waiting for your comments