toggleClass – jQuery method for switching css classes

I was asked:

Which jQuery method is used to switch between adding/removing one or more classes (for CSS) from selected elements?

The answer to this query is .toggleClass() method of jQuery.

For example, if we have a div like this:

<div class="original">Some text here</div>

Now if we add this to jquery:

$("div.original").toggleClass("added")

It will change our div’s html code to:

<div class="original added">Some text here</div>

If we apply the same jQuery again the second time to this new code, it will toggle it back to the original version.

Leave a Reply

Your email address will not be published.