Easy Tutorial
❮ Misc Type Jquery Dom Add ❯

jQuery - Getting and Setting CSS Classes


With jQuery, it is easy to manipulate CSS elements.


jQuery CSS Operations

jQuery has several methods for CSS manipulation. We will learn about the following:


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 within the addClass() method:

Example

$("button").click(function(){
  $("body div:first").addClass("important blue");
});

jQuery removeClass() Method

The following example demonstrates how to remove specified class attributes from different elements:

Example

$("button").click(function(){
  $("h1,h2,p").removeClass("blue");
});

jQuery toggleClass() Method

The following example shows how to use the jQuery toggleClass() method. This method toggles between adding/removing classes from the selected elements:

Example

$("button").click(function(){
  $("h1,h2,p").toggleClass("blue");
});

jQuery css() Method

We will discuss the jQuery css() method in the next chapter.

❮ Misc Type Jquery Dom Add ❯