How to Add or Remove class in jQuery ?
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:
- Adding a class:
$('selector').addClass(class_name);
- Removing a class:
$('selector').removeClass(class_name);
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" > <!-- Including jQuery --> < 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" > <!-- Image added using img tag with src attribute --> < 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
Please Login to comment...