jQuery Get and Set CSS Classes
- Previous page jQuery delete
- Next page jQuery css()
Through jQuery, it is easy to operate CSS elements.
jQuery CSS Operations
jQuery has several methods for CSS operations. We will learn the following:
- addClass() - Add one or more classes to selected elements
- removeClass() - Remove one or more classes from selected elements
- toggleClass() - Perform add/remove class switch operation on selected elements
- css() - Set or return style properties
Example Stylesheet
The following stylesheet will be used for all examples on this page:
.important { font-weight:bold; font-size:xx-large; } .blue { color:blue; }
jQuery addClass() method
The following example shows how to add class attributes to different elements. Of course, you can also select multiple elements when adding classes:
Example
$("button").click(function(){ $("h1,h2,p").addClass("blue"); $("div").addClass("important"); });
You can also specify multiple classes in the addClass() method:
Example
$("button").click(function(){ $("#div1").addClass("important blue"); });
jQuery removeClass() method
The following example shows how to remove a specified class attribute from different elements:
Example
$("button").click(function(){ $("h1,h2,p").removeClass("blue"); });
jQuery toggleClass() method
The following example will demonstrate how to use the jQuery toggleClass() method. This method performs the add/remove class switch operation on the selected elements:
Example
$("button").click(function(){ $("h1,h2,p").toggleClass("blue"); });
jQuery css() method
We will explain the jQuery css() method in the next chapter.
jQuery HTML Reference Manual
For the complete content of the jQuery CSS method, please visit our jQuery CSS Operation Manual
- Previous page jQuery delete
- Next page jQuery css()