jQuery has several methods for CSS manipulation. We will look at the following methods.
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
Now click on Add classes to elements button to add class on selected item.
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
Now click on Remove classes to elements button to removes a specific class attribute from different elements(h1, h2, p).
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
Now click on toggle class button to toggles between adding/removing classes from the selected elements.