The jQuery hasClass() method checks whether the specified class name exist in the selected elements. It returns a ‘true’ value when it finds the specified class is present. You will get ‘false’ if the class is not present in the element.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of the parameters is given below.
Parameter Name | Description |
---|---|
selector | The selector is the required field used to select the elements. You have to use the tag name, class name, or id of the elements to select. |
className | Specify the class name to check if present in the selected element. |
jQuery hasClass() Method to Check If Class is Exist
When you have to check the existence of the class name in the element, you have to use this method. If you want to add a class name to the element, you have to first check whether it’s already present in the element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<script> $(document).ready(function(){ $('.myhasclassbtn').click(function(){ var myclass = $("p").hasClass("mypara"); alert(myclass); }); }); </script> <style> .mypara{ padding:10px; border:1px solid #ccc; } </style> <p>Click the below button to check if class name 'mypara' is exist or not.</p> <button type="button" class="myhasclassbtn">Click to Check Class</button><br><br> <p class="mypara">This is my paragraph</p> |
Output
Click the below button to check if class name ‘mypara’ is exist or not.
This is my paragraph
You have to click the button given above to get the result in the alert box. The example shows that the specified class is present in the selected element. After you find the existence of the class name, you can add another class using the jQuery addClass() method.
You may also like to read
I hope you like this tutorial on jQuery hasClass() method. If you have any queries regarding the tutorial, please comment below.
References