IMG-LOGO
Home Course Get and Set Classes in CSS

Get and Set Classes in CSS

by MH RISHAD - 08 May 2019
IMG

Manipulate the style of elements Is easest.

jQuery can be Manipulating CSS

jQuery has many of methods for CSS manipulation. Let’s look at the following methods:

                                       Methods:

addClass() - Adds 1 or more than 1 classes in selected elements/contents

removeClass() - Removes 1 or more than 1 classes in selected elements/contents

toggleClass() - Toggles between adding/removing classes from the selected elements/contents

css() - Sets or returns style attribute

Example Stylesheet

Following stylesheet will be used for all the examples on this page:

.need {
  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. And we can select multiple elements, when adding classes:

Example

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

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

Example

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

jQuery removeClass() Method

The following example shows to remove a specific class attribute from different elements:

Example

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

jQuery toggleClass() Method

The following example will show 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");
});

 

Thank You

Share:

Leave a Comment

Required fields are marked *