Java Reference
In-Depth Information
This code achieves the same results as before but with fewer keystrokes.
Note Most jQuery methods return a jQuery object, allowing you to
immediately call methods one after another.
But you can simplify this code even more because you can pass both CSS class names to addClass() ,
like this:
content.addClass("class-three class-four");
You just have to separate the class names with a space.
The removeClass() method removes one or multiple classes:
content.removeClass("class-one");
This code uses the removeClass() method to remove the class‐one class from the element. If you
need to remove multiple classes, simply separate them with a space, like this:
content.removeClass("class-two class-four");
As you can see, the same concepts that let you add classes to an element apply to removing classes.
But there's one very important difference: The arguments you pass to removeClass() are optional.
If you do not pass any arguments to removeClass() , it will remove all classes from the element:
content.removeClass();
This code, therefore, removes all CSS classes from the element(s) represented by the content object.
toggling Classes
Although the addClass() and removeClass() methods are certainly useful, sometimes you need to
just toggle a class. In other words, you remove a class if it's present or add it if it's not. jQuery makes
this easy with the aptly named toggleClass() method:
content.toggleClass("class-one");
This code first toggles the class‐one class. If it is already applied to the element, jQuery removes
class‐one . Otherwise, it adds class‐one to the element's class list.
This behavior is useful when you need to add or remove a specific class from the element. For
example, the following code is vanilla JavaScript and DOM coding to add and remove a specific CSS
class depending on the type of event:
var target = e.target;
if (e.type == "mouseover") {
target.className = "class-one";
} else if (e.type == "mouseout") {
 
Search WWH ::




Custom Search