how to add or remove class using jquery
Last updated:23rd Apr 2022
In this post, learn how can you add or remove a CSS class in Jquery. you can easily add or remove a class by clicking on the same button.
add or remove CSS class in jquery
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
.mystyle {
padding: 30px;
margin:5px;
background-color: red;
color:white;
border: 1px solid green;
font-size: 20px;
}
</style>
</head>
<body>
<p>Click the "clickme" button to remove the "mystyle" class from the div element which contain id mydiv:</p>
<button id="clickme">click me</button>
<div id="mydiv">
This is a DIV element.
</div>
<script>
$(document).ready(function() {
$("#clickme").click(function() {
if($("#mydiv").hasClass("mystyle")){
$("#mydiv").removeClass("mystyle");
}
else {
$("#mydiv").addClass("mystyle");
}
});
});
</script>
</body>
</html>
Explanation for adding or remove class
- when you click on the 'click me' button, the jquery code will get executed.
- in jquery, It will check whether
mystyle
a class is present or not. i.eif($("#mydiv").hasClass("mystyle")).
- if
mystyle
class is present then it will remove class by using code,$("#mydiv").removeClass("mystyle");
. - if a class is not present then else part will get executed and
mystyle
class will get added.$("#mydiv").addClass("mystyle");
.