Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

jQuery CSS class


May 07, 2021 jQuery


Table of contents


jQuery - Gets and sets the CSS class


jQuery makes it easy to manipulate CSS elements.


jQuery operates CSS

jQuery has several methods for performing CSS operations. We'll learn the following:


The instance style sheet

The following style sheets 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 properties to different elements. Of course, when you add a class, you can also select multiple elements:

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

Try it out . . .

You can also specify multiple classes in the addClass() method:

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

Try it out . . .

Tip: Want to know about the specific exercise of jQuery using the addClass() method to add class to an element? Please refer to this site's jQuery programming practice!


jQuery removeClass() method

The following example shows how to remove the specified class property from different elements:

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

Try it out . . .

Tip: From the example above, have you learned how to remove class properties in jQuery? Perhaps you can also consolidate your knowledge by programming the "Class with jQuery to remove HTML elements" section of the jQuery programming battle on this site!


jQuery toggleClass() method

The following example shows how to use the jQuery toggleClass() method. This method switches the selected elements to add/remove classes:

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

Try it out . . .



jQuery css() method

We'll cover the jQuery css() approach in the next chapter.

Related articles

If you need the full contents of the jQuery CSS method, please visit our jQuery Reference Manual - CSS Operations!