Advertisement

Google Ad Slot: content-top

jQuery CSS Classes


jQuery Manipulating CSS


In jQuery, you can easily get, add, remove, or toggle CSS classes using built-in methods. These are useful for dynamically changing the look and behavior of elements.

Method

Description

.addClass()

Adds one or more classes to selected elements

.removeClass()

Removes one or more classes from selected elements

.toggleClass()

Adds/removes a class based on its current state

.hasClass()

Checks if the selected element has a specific class

Example Stylesheet


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


.highlight {
  background-color: yellow;
  font-weight: bold;
 }

.blue {
  color: blue;
}

jQuery addClass() Method


he following example shows how to add class attributes to different elements. Of course you can select multiple elements, when adding classes:

Example
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, h2, p").addClass("blue");
$("div").addClass("highlight");
});
});
</script>
Try it yourself

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

Example
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").addClass("highlight blue");
});
});
</script>
Try it yourself

jQuery removeClass() Method

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

Example
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, h2, p").removeClass("blue");
});
});
</script>
Try it yourself

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
<script>
$(document).ready(function(){
$("#checkBtn").click(function(){
if ($("#myDiv").hasClass("highlight")) {
alert("The element has the 'active' class.");
} else {
alert("The element does NOT have the 'active' class.");
}
});
});
</script>
Try it yourself