addClass, removeClass, hasClass and toggleClass in jQuery

In this post, I will explain about some of the basic but useful jQuery css selectors. These CSS selectors are used to add or remove CSS class, to check whether element has specific css class associated with it or not. Believe me these are basic, but pretty useful.

Add cssClass to specific element

$('#element').addClass('myclass');

Remove cssClass from specific element

$('#element').removeClass('myclass');

Check whether element has the cssClass associated with it

$('#element').hasClass('myclass');

Add or remove cssClass using single css Selector

$('#element').toggleClass('myclass');

.toggleClass() is combination of .addClass() and .removeClass(). It first checks, whether specified cssClass is associated with element or not. if not then it adds it, otherwise it removes it. This is very useful when on button click you want to add and remove css class for any element.

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...