Manipulating CSS classes is one of the most common uses for jQuery.
Instead of changing inline CSS styles individually, it is much cleaner to toggle predefined classes.
jQuery provides three highly optimized methods for class manipulation:
addClass() - Adds one or more classes to the selected elements.removeClass() - Removes one or more classes from the selected elements.toggleClass() - Toggles between adding and removing classes from the selected elements.The addClass() method attaches a class to an element without overwriting its existing classes.
You can also pass multiple classes at the same time by separating them with a space.
$("button").click(function(){
$("h1, h2, p").addClass("blue");
$("div").addClass("important blue");
});
If an element has a class you no longer want, removeClass() takes care of it.
This is perfectly suited for removing "active" states from navigation menus.
$("button").click(function(){
$("h1, h2, p").removeClass("blue");
});
The toggleClass() method is incredibly powerful for interactive UI elements.
It checks if a class exists. If it exists, it removes it. If it doesn't exist, it adds it.
$("button").click(function(){
$("h1, h2, p").toggleClass("blue");
});
Which method is best for creating a button that switches a dark-mode theme on and off?