In this tutorial, you will learn how to use jQuery hasClass() method. This method checks if a specified class assigned to the specified element.
Syntax of hasClass() method
$(selector).hasClass(classname)
Here, classname
specifies the class that needs to be checked. This method returns true if the element selected by the selector, has the classname
assigned to it.
jQuery hasClass() method example
In the following example, a class big
is assigned to a paragraph. On the button click event, we are using hasClass() method to check whether the class big
is assigned to any paragraph present in the html page.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("p").hasClass("big"));
});
});
</script>
<style>
.big {
font-size: 200%;
color: green;
}
</style>
</head>
<body>
<h1>jQuery hasClass() example on BeginnersBook.com</h1>
<p class="big">This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the last paragraph.</p>
<button>Is "big" class assigned to any p element?</button>
</body>
</html>
Output Screen before the click event:
Output Screen after the click event:
jQuery hasClass() Example 2: Displaying result on same page
In this example, we are displaying the result of the hasClass() method in the html page itself. Here, we have two paragraphs, the first paragraph has the id “para1” and the second paragraph has the id “para2”. We are checking whether the first and second paragraph are green using the hasClass() method. This method returns boolean value true or false.
<!DOCTYPE html>
<html>
<head>
<title>jQuery hasClass() example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#result1").text( $("p#para1").hasClass("green") );
$("#result2").text( $("p#para2").hasClass("green") );
});
</script>
<style>
.green { color:green; }
.red { color:red; }
</style>
</head>
<body>
<h1>jQuery hasClass() example on BeginnersBook.com</h1>
<p class="green" id="para1">This is first paragraph.</p>
<p class="red" id="para2">This is second paragraph.</p>
Is first paragraph green? <div id="result1">I</div>
is second paragraph green? <div id="result2"></div>
</body>
</html>
Output:
Leave a Reply