The addClass() or removeClass() methods are used to add the CSS classes when there is a need to add to our webpage when there is some event listener or to create some kind of effect.
In this article, let us see how can we add a CSS class or remove a CSS class in jQuery.
Syntax:
Example: The following example adds a class that makes the background colour black when clicked on ADD CLASS button and also removes that added class when clicked on the REMOVE CLASS button.
HTML
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta http-equiv = "X-UA-Compatible"
content = "IE=edge" >
< meta name = "viewport" content =
"width=device-width, initial-scale=1.0" >
< script src =
integrity =
"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin = "anonymous" >
</ script >
< style >
h1 {
color: #006600;
}
button {
color: white;
background-color: #006600;
width: auto;
height: 30px;
}
body {
text-align: center;
}
div {
margin: 10px;
height: 150px;
width: 150px;
position: relative;
text-align: center;
display: flex;
left: 215px;
}
.bg-black {
background-color: black;
}
</ style >
</ head >
< body >
< h1 >Geeks For Geeks</ h1 >
< button id = "btnadd" > ADD CLASS </ button >
< button id = "btnremove" > REMOVE CLASS </ button >
< div id = "GFG_IMAGE" >
< img src =
height = '150px' width = '150px' >
< img >
</ div >
< script >
$(document).ready(function() {
$('#btnadd').click(function() {
$('img').addClass('bg-black');
});
$('#btnremove').click(function() {
$('img').removeClass('bg-black');
});
});
</ script >
</ body >
</ html >
|
Output:

Add class and remove class
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 Aug, 2021
Like Article
Save Article