jQuery hasClass() Method

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.

jQuery hasClass() Method

Syntax

The syntax of this method is given below:-

Check if a class is exist
$(selector).hasClass(className)

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

Test it Live

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