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.
The following example will remove the class .page-header from the <h1> and the class .hint and .highlight from the <p> elements on button click.
Example
<!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>
When the removeClass() method is called without an argument it will remove all the classes from the selected elements. Here’s an example:
Example
<!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();
$("p").removeClass();
});
});
</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; if an element does not have the class, then it is added i.e. toggle classes.
Example
<!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>