If you want to add or remove CSS classess from your HTML page, jQuery library provides certain methods like jQUery hasClass(), jQuery addClass(), and jQuery removeClass(). A single method jQuery toogleClass() method perform both add and remove the Class alone on the occuring of some event.

So, let’s start learning each method one by one.

jQuery hasClass() Method

jQuery hasClass method is used to check the existence of the class in the HTML element. You can perform some action after checking if the CSS class already present in the element.

Output


This is the jQuery Tutorial of check CSS class existence.

The above example checks the existence of the CSS class when you click the button. If the class is present in the element, it gives you true in the alert and if not present, it gives you false alert.

The element present above contains the CSS class and the alert gives you true as the output of the jQuery hasClass().

jQuery addClass() Method

jQuery addClass method adds the class to the HTML element you have selected. If the element already contains the CSS class, it inserts the class again.

Output


This is the jQuery Tutorial of add CSS class.

The above example contains the button to click and add the CSS class. The CSS class contains some styles properties like background and padding. When you add this class to the HTML element, the CSS properties automatically applies to the selected HTML element

On click of the button, the HTML element changes its appearance on the addition of the CSS class.

jQuery removeClass() Method

jQuery removeClass() removes the CSS class from the selected HTML element. If the element contains the CSS class more than one times, it removes all the classes mentioned in the jQuery removeClass().

Output


This is the jQuery Tutorial of remove CSS class.

The above example removes the CSS class on click of the button. The selected HTML element change its overall appearance and styling after the removal of the CSS class.

jQuery toggleClass() Method

The jQuery toggleClass() method perform both add and remove task from the occurring of some event. If the class already present in the selected HTML element, jQuery toggleClass() remove the class and if not present, it adds the CSS class from the HTML element.

Output


This is the jQuery Tutorial of toggle CSS class.

Click the button given above to see the action perform by the toggleClass(). In addition and removal of the class, the HTML element changes its appearance.

You must also learn:-

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.