English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
One of the most important parts of jQuery is the possibility of manipulating the DOM.
jQuery provides effective methods for operating element styles.
In this chapter, we will explain how to add or remove CSS classes in the DOM.
With jQuery, we can easily manipulate the styles of elements.
We have the following jQuery methods for CSS operations:
Below, we will show you how to use each method.
jQuery addClass()The method adds one or more class names to the selected element.
The following example adds a class name to the first <p> element:
$("button").click(function(){ $("p:first").addClass("highlight"); });Test to see‹/›
Multiple classes (separated by spaces) can be added to the selected element at one time, as shown below:
$("button").click(function(){ $("p:first").addClass("highlight big"); });Test to see‹/›
jQuery removeClass()The method removes one or more class names from the selected elements.
The following example removes a class name from all <p> elements:
$("button").click(function(){ $("p").removeClass("highlight"); });Test to see‹/›
One can remove more than one class (separated by spaces) from a group of selected elements, as shown below:
$("button").click(function(){ $("p").removeClass("highlight big"); });Test to see‹/›
If the class name is not specified in the parameter, all classes will be removed:
$("button").click(function(){ $("p").removeClass(); });Test to see‹/›
jQuery toggleClass()The method toggles in/Toggle between removing one or more class names from the selected element.
The following example toggles between adding and removing the "anotherClass" class name for all <p> elements:
$("button").click(function(){ $("p").toggleClass("anotherClass"); });Test to see‹/›
This method checks the specified class name for each element:
If the class name is missing, it will be added
If the class name has already been set, it will be removed
jQuery css()method retrieves or sets one or more style properties of the selected element.
jQuery css()methods will be explained in the next chapter.
For a complete reference of CSS methods, please visit ourjQuery HTML / CSS Reference.