Check if any <p> element has a class named "intro":
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>/*from w w w .j a v a2 s .c om*/ <script> $(document).ready(function(){ $("button").click(function(){ document.getElementById("demo").innerHTML = $("p").hasClass("intro"); }); }); </script> <style> .intro { font-size: 120%; color: red; } </style> </head> <body> <p id="demo"></p> <h1>This is a heading</h1> <p class="intro">This is a paragraph.</p> <p>This is another paragraph.</p> <button>Does any p element have an "intro" class?</button> </body> </html>
The hasClass()
method checks if any of the selected elements have a specified class name.
It returns true if any of the selected elements has the specified class name.
$(selector).hasClass(classname)
Parameter | Optional | Description |
---|---|---|
classname | Required. | the class name to search for in the selected elements |