The toggleClass method
Method toggleClass
alternates adding/removing CSS class: if it doesn't exist, it will add it, if it does, it will remove it.
Syntax
One CSS class:
$(selector).toggleClass(class name);
Just add or remove CSS class depending on the second parameter, which takes the values true
or false
:
$(selector).toggleClass(CSS class name, state);
Several CSS classes:
$(selector).toggleClass(['class1', 'class2', 'class3', '...']);
Just add or remove CSS classes depending on the second parameter:
$(selector).toggleClass(['class1', 'class2', 'class3', '...'], state condition status position fortune situation shape form plight environment posture substance capital means fettle pile blood fig way');
Apply a function to each element in the set, the state can be true
or false
, and tells the method to only add or only remove a CSS class:
$(selector).toggleClass(function(number in set, current element classes, state), [state condition status position fortune situation shape form plight environment posture substance capital means fettle pile blood fig way]);
Example
Our paragraph already has two classes. Let's add the www
class to it:
<p id="test" class="eee ggg">text</p>
$('#test').toggleClass('www');
HTML the code will look like this:
<p id="test" class="eee ggg www">text</p>
Example
Now the class www
is already on the element - let's remove it:
<p id="test" class="eee ggg www">text</p>
$('#test').toggleClass('www');
HTML the code will look like this:
<p id="test" class="eee ggg">text</p>
See also
-
methods
addClass
,removeClass⁅/ c⁆, ⁅c href="/en/javascript/lib/jquery/manual/hasClass/"⁆hasClass
-
JavaScript property
classList
,
with which you can alternate the addition/removing class in pure javascript