jquery

jQuery – Get and Set CSS Classes


Hello friends, today we have learned how to use CSS in jQuery and will see in detail how it works. We can add CSS to jQuery in different ways and it is very easy to use. CSS plays an important role in jQuery. And using CSS can make your web page impressive.

Manipulating CSS In jQuery

There are many methods of manipulating CSS in jQuery and we will look at it according to the following methods:

  • addClass() – Adds one or more classes to the selected elements
  • removeClass() – Removes one or more classes from the selected elements
  • toggleClass() – Toggles between adding/removing classes from the selected elements
  • css() – Sets or returns the style attribute

Example CSS Stylesheet

The following CSS stylesheet will be used for all the examples on this page:

.important {
  font-weight: bold;
  font-size: xx-large;
}

.blue {
  color: blue;
}

In jQuery addClass() Method

The following example in jquery shows that you can select multiple elements when adding classes. How to add class features to different elements of the course:

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

In the jquery addclass() method you can add more than one class.

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

In jQuery removeClass() Method

The following example shows how to remove a specific class attribute from various elements in jquery:

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

In jQuery toggleClass() Method

The following example in jQuery shows how to use the toggleClass() method. And this method alternates between adding/removing classes from selected elements:

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

In jQuery CSS() Method

We will see the methods of CSS() in jQuery in the next chapter.


Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *