addClass() method of Jquery
Adding a class to an element in jquery is very simple. The classes can be added using addClass() method. One or more classes can be added to element. Single class can be added to multiple elements. The following example shows adding single class to multiple elements and also adding more than one class to single element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<!DOCTYPE html><html> <head> <script src="http://code.jquery.com/jquery-1.8.3.js"></script> <script> $(function(){ $("button").click(function(){ $("p,h3").addClass("htmlClass"); $("div").addClass("cssClass"); }); }); </script> <style> .htmlClass { font-style: italic; color: #D02357; } .cssClass { font-weight: bold; color: #28721B; } </style> </head> <body> <p> Jquery is a Javascript library!! </p> <h3> This is from j2eereference.com</h3> <div> Learn jQuery from j2eereference.com </div> <button>Click to add class</button> </body> </html> |
On click output will be :
removeClass() method of Jquery
The classes can be removed using removeClass() method. One or more classes can be removed of an element.The following example shows removing single class of multiple elements and removing more than one class of single element.
Above same example is modified to remove the classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.8.3.js"></script> <script> $(function(){ $("button").click(function(){ $("p,h3").removeClass("htmlClass"); $("div").removeClass("cssClass"); }); }); </script> <style> .htmlClass { font-style: italic; color: #D02357; } .cssClass { font-weight: bold; color: #28721B; } </style> </head> <body> <p class="htmlClass"> Jquery is a Javascript library!! </p> <h3 class="htmlClass"> This is from j2eereference.com </h3> <div class="cssClass"> Learn jQuery from j2eereference.com </div> <button>Click to remove css class</button> </body> </html> |
On click output will be :