jQuery provides several methods, such as addClass()
, removeClass()
, toggleClass()
, etc. to manipulate the CSS classes /add and remove css classes assigned to HTML elements.
jQuery addClass()
Method
The jQuery addClass()
method adds one or more classes to the selected elements.
$("h1").addClass("page-header");
$("#abc").addClass("page-header");
$(".abc").addClass("page-header");
Example 1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery addClass() Demo</title>
<style>
.page-header{
color: red;
text-transform: uppercase;
}
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1").addClass("page-header");
$("p.hint").addClass("highlight");
});
});
</script>
</head>
<body>
<h1>Demo Text</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
<p class="hint"><strong>Tip:</strong> Lorem Ipsum is dummy text.</p>
<button type="button">Add Class</button>
</body>
</html>
jQuery removeClass()
Method
Similarly, you can remove the classes from the elements using the jQuery removeClass() method. The removeClass() method can remove a single class, multiple classes, or all classes at once from the selected elements.
$("h1").removeClass("page-header");
Example 2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery removeClass() Demo</title>
<style>
.page-header{
color: red;
text-transform: uppercase;
}
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1").removeClass("page-header");
$("p").removeClass("hint highlight");
});
});
</script>
</head>
<body>
<h1 class="page-header">Demo Text</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
<p class="hint highlight"><strong>Tip:</strong> Lorem Ipsum is dummy text.</p>
<button type="button">Remove Class</button>
</body>
</html>
jQuery toggleClass()
Method
The jQuery toggleClass()
add or remove one or more classes from the selected elements in such a way that if the selected element already has the class, then it is removed;
$("#abc").toggleClass("highlight");
Example 3
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery toggleClass() Demo</title>
<style>
p{
padding: 10px;
cursor: pointer;
font: bold 16px sans-serif;
}
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).toggleClass("highlight");
});
});
</script>
</head>
<body>
<p>Click on me to toggle highlighting.</p>
<p class="highlight">Click on me to toggle highlighting.</p>
<p>Click on me to toggle highlighting.</p>
</body>
</html>