jQuery get and set CSS class

By jQuery, it can easily operate on CSS elements.


jQuery CSS operation

jQuery has several methods of CSS operation. We will learn the following:

  • addClass () - Add one or more categories to the selected element
  • removeClass () - Deletes one or more elements selected from the class
  • toggleClass () - for the selected element in the Add / Remove class switching operation
  • css () - Sets or returns style attributes

Examples of stylesheets

The following stylesheet will be used for all the 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 a class attribute to the different elements. Of course, when you add a class, you can also select multiple elements:

Examples

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

You can also specify in addClass () method in multiple categories:

Examples

$("button").click(function(){
$("#div1").addClass("important blue");
});



jQuery removeClass () method

The following example shows how to delete the specified class attribute different elements:

Examples

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



jQuery toggleClass () method

The following example shows how to use jQuery toggleClass () method. The method of switching operations selected elements Add / Remove class:

Examples

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



jQuery css () method

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