WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

jQuery - Get and Set CSS Classes


With jQuery, it is anything but difficult to control the CSS of elements.



jQuery Manipulating CSS

jQuery has a few techniques for CSS control. We will take a gander at the following methods:

  • addClass() - Adds at least one classes to the chose elements
  • removeClass() - Removes at least one classes from the chose elements
  • toggleClass() - Toggles between including/expelling classes from the chose elements
  • css() - Sets or returns the style attribute

Example Stylesheet

The following template will be utilized for every one of the precedents on this page:

.essential {
    textual style weight: bold;
    text dimension: xx-large;
}

.blue {
    shading: blue;
}

jQuery addClass() Method

The following precedent tells the best way to add class ascribes to various components. Obviously you can choose numerous components, while including classes:

Example

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

You can likewise indicate various classes inside the addClass() method:

Example

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

jQuery removeClass() Method

The following model tells the best way to expel a particular class property from various elements:

Example

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

jQuery toggleClass() Method

The following model will tell the best way to utilize the jQuery toggleClass() technique. This technique flips between including/expelling classes from the chose elements:

Example

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

jQuery css() Method

The jQuery css() technique will be clarified in the following chapter.