• jQuery Video Tutorials

jQuery hasClass() Method



The hasClass() method in jQuery is used to check whether any of the selected elements have the specified class name. It checks if the specified class name is present on any of the elements in the jQuery object.

Syntax

Following is the syntax of hasClass() method in jQuery −

$(selector).hasClass(classname)

Parameters

This method accepts the following parameter −

  • classname: A string representing the class name to check for.

Return Value

The method returns true if any of the selected elements have the specified class name; otherwise, it returns false.

Example 1

In the following example, we are using the hasClass() method to check if any <div> element has a class named "highlight" −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    if ($('div').hasClass('highlight')) {
        alert("A div with the class 'highlight' exist.");
    } else {
        alert("A div with the class 'highlight' does not exist.");
    }
  })
});
</script>
</head>
<body>
<div class="highlight">Div element with class "highlight".</div>
<div class="one">Div element with class "one".</div>
<div class="two">Div element with class "two".</div>
<button>Click to check</button>
</body>
</html>

When we click on the button, it returns an alert stating that there is a <div> element with the class named "highlight".

Example 2

Here, we are checking if any <p> element has a class named "highlight" −

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $('p').each(function(){
      if ($(this).hasClass('highlight')) {
        $(this).css("background-color", "yellow");
      }
    });
  });
});
</script>
</head>
<body>
<p class="highlight">Paragraph element with class "highlight".</p>
<p class="one">Paragraph element with class "one".</p>
<p class="two">Paragraph element with class "two".</p>
<button>Click to check</button>
</body>
</html>

After clicking the button, it highlights the <p> element that has a class named "highlight" with a yellow-colored background.

jquery_ref_html.htm
Advertisements