jQuery hasClass() with Examples


The hasClass() method in jQuery is used to check if any of the selected elements is having a specified class name.

Syntax

The syntax is as follows −

$(selector).hasClass(classname)

Above, the parameter class name is the class name to search for in the selected elements.

Example

Let us now see an example to implement the jQuery hasClass() method

 Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("button").click(function(){
         alert($("h2").hasClass("demo"));
      });
   });
</script>
</head>
<body>
<h2>Student Info</h2>
<h2 class="demo">Teacher Info</h2>
<button>Click me</button>
<p></p>
</body>
</html>

Output

This will produce the following output−

 

Click the “Click me” button to display whether any <h2> element has class “demo”: 

Updated on: 30-Dec-2019

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements