Adds one or more classes to each element in the set of matched elements. .addClass(class) |
It's important to note that this method does not replace a class; it simply adds the class.
More than one class may be added at a time, separated by a space, to the set of matched elements, like so: $('p').addClass('myclass yourclass')
.
This method is often used with .removeClass()
to switch elements' classes from one to another, like so:
$('p').removeClass('myclass noclass').addClass('yourclass')
Here, the myclass
and noclass
classes are removed from all paragraphs, while yourclass
is added.
Removes one or all classes from each element in the set of matched elements. .removeClass([class]) |
If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.
More than one class may be removed at a time, separated by a space, from the set of matched elements, like so: $('p').removeClass('myclass yourclass')
.
This method is often used with .addClass()
to switch elements' classes from one to another, like so:
$('p').removeClass('myclass').addClass('yourclass')
Here, the class myclass
is removed from all the paragraphs, while yourclass is added.
To replace all existing classes with another class, use .attr('class','new-class')
instead.
If the class is present, .toggleClass(class) |
This method takes one or more class names as its parameter. If an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added. For example, we can apply .toggleClass()
to a simple <div>
:
<div class="tumble">Some text.</div>
The first time we apply $('div.tumble').toggleClass('bounce')
, we get the following:
<div class="tumble bounce">Some text.</div>
The second time we apply $('div.tumble').toggleClass('bounce')
, the <div>
class is returned to the single tumble
value:
<div class="tumble">Some text.</div>
Applying .toggleClass('bounce spin')
to the same <div>
alternates between <div class="tumble bounce spin'>
and <div class="tumble'>
.