jQuery hasClass – Using hasClass method with jQuery if statement


jQuery hasClass – Using hasClass method with jQuery if statement

jQuery hasClass – Using hasClass method with jQuery if statement

jQuery hasClass method

The hasClass method of jQuery takes the class name as parameter and checks if a class exists in the specified element(s).

See an example of hasClass

In the jQuery hasClass method, if the class name is found in specified element it will return true and if not found it will return false.

On that basis, you may perform some actions like if a given class name is not found, you can add a class to that element, show some alert etc.

The example below will show you how to use jQuery if..else statement as well if the class is found or not with the hasClass method.

Syntax of hasClass method

The syntax of hasClass jQuery method is:

$(“element”).hasClass(“Class_to_be_found”);

Example of using hasClass with if..else statement

The example below will check if a class exists in a div element or not. As you click on the button “Click to check if a class exists in div” it will show a message in paragraph whether the class exists or not.

The code is handled in the if…else statement to show in the paragraph.

jQuery hasClass

Experience this example online



Adding a class example

In the following example, if the given class does not exist in the specified element, by using jQuery hasClass method, we will add a class to add CSS to the div element by using jQuery addClass method.

jQuery hasClass addclass

Experience this example online



After you clicked the button and the class is added to the div element, if you click the button again it will check if the class exists or not in div element again. As class has been added, the message should be shown as “Class exists”.

Related  jQuery addClass method | jQuery $.append | jQuery $.prepend



Was this article helpful?