This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

jQuery CSS Classes

jQuery CSS Classes

jQuery has several methods for CSS manipulation. We will look at the following methods.

  1. AddClass()
  2. RemoveClass()
  3. ToggleClass()

1. jQuery AddClass() method

This method is used to add one or more classes to the selected elements. In below example you can add class Red for h1, h2, p elements..

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, h2, p").addClass("red");
$("div").addClass("fontclass");
});
});
</script>
<style>
.fontclass {
font-weight: bold;
font-size: xx-large;
}
.red {
color: Red;
}
</style>
</head>
<body>

<h1>Heading1 </h1>
<h2>Heading2</h2>
<p>paragraph1</p>
<p>paragraph2</p>
<div>This is some important text!</div><br>
<button>Add classes to elements</button>

</body>
</html>

Output

jquery cssclass method

Now click on Add classes to elements button to add class on selected item.

jquery cssclass method

2. jQuery RemoveClass() method

This method is used to removes one or more classes from the selected elements. The below example shows how to remove a specific class attribute from different elements.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, h2, p").removeClass("red");

});
});
</script>
<style>
.red {
color: Red;
}
</style>
</head>
<body>

<h1 class="red">Heading1 </h1>
<h2 class="red">Heading2</h2>
<p class="red">paragraph1</p>
<p>paragraph2</p>
<div>This is some important text!</div><br>
<button>Remove classes to elements</button>

</body>
</html>

Output

jquery cssclass method

Now click on Remove classes to elements button to removes a specific class attribute from different elements(h1, h2, p).

jquery cssclass method

3. jQuery ToggleClass() method

This method is used to toggles between adding/removing classes from the selected elements.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, h2, p").toggleClass("red");

});
});
</script>
<style>
.red {
color: Red;
}
</style>
</head>
<body>
<h1 class="red">Heading1 </h1>
<h2 class="red">Heading2</h2>
<p class="red">paragraph1</p>
<p>paragraph2</p>
<div>This is some important text!</div><br>
<button>Toggle class</button>
</body>
</html>

Output

jquery cssclass method

Now click on toggle class button to toggles between adding/removing classes from the selected elements.

jquery cssclass method
Prev Next