How CSS classes can be manipulated in HTML using jQuery ?
The common manipulation of classes includes actions like add class or remove class from the HTML tags.
The following classes are used for the manipulations.
1. addClass() method: The purpose of addClass() function is to add one or more classes to the specified element or tag.
Syntax:
$('selector expression').addClass('class name');
Example:
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 = </ script > < style > p{ border:1px solid black; text-align: center; padding:2rem; margin: 2rem; } .bgred{ background-color: red; } button{ margin:0 10rem; } </ style > </ head > < body > < center > < h2 style = "color:green" >GeeksforGeeks</ h2 > < p class = "" >Hi this is paragraph</ p > < button id = "btn" >Change background</ button > </ center > < script > $('button').click(()=>{ $('p').addClass('bgred') }) </ script > </ body > </ html > |
Output:

2. removeClass() method: We use the removeClass() function to remove one or more or all classes from the specified element or tag.
Syntax:
$('selector expression').removeClass('class name');
Example:
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 = </ script > < style > p{ border:1px solid black; text-align: center; padding:2rem; margin: 2rem; } .bgred{ background-color: red; } button{ margin:0 10rem; } </ style > </ head > < body > < center > < h2 style = "color:green" >GeeksforGeeks</ h2 > < p class = "bgred" >Hi this is paragraph</ p > < button id = "btn" >Change background</ button > </ center > < script > $('button').click(()=>{ $('p').removeClass('bgred'); }) </ script > </ body > </ html > |
Output:

3. toggleClass() method: We use the toggleClass() function to simultaneously add or remove the class to the specified element or tag.
Syntax:
$('selector expression').addClass('class name');
Example:
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 = </ script > < style > p{ border:1px solid black; text-align: center; padding:2rem; margin: 2rem; } .bgred{ background-color: red; } button{ margin:0 10rem; } </ style > </ head > < body > < center > < h2 style = "color:green" >GeeksforGeeks</ h2 > < p class = "bgred" >Hi, this is paragraph</ p > < button id = "btn" >Change background</ button > </ center > < script > $('button').click(()=>{ $('p').toggleClass('bgred'); }) </ script > </ body > </ html > |
Output:

Please Login to comment...