jQuery removeClass


A pair of the removeClass and addClass essentially replace a class. If you checked the last example in the previous post , you may have noticed the issue with dynamically changing the class associated with selected element.

Here is the example that shows the usage of the removeClass example.

  1. <!DOCTYPE html>
  2. <!-- Referencedesigner.com Example -->
  3. <html>
  4. <head>
  5. <style>
  6. .highlightyellow { background:yellow; }
  7. .highlightpink { background:pink; }
  8. </style>
  9. <script src="http://code.jquery.com/jquery-latest.js"></script>
  10. </head>
  11. <body>
  12. <p>Referencedesigner.com removeClass example</p>
  13. <p>Second Paragraph</p>
  14. <p>This last line will get highlighted when button "Highlight last line" is pressed </p>
  15. <button id = "button1">Highlight Last Line with yellow</button>
  16. <button id = "button2">Highlight Last Line with Pink</button>
  17. <script>
  18. $("button#button1").click(function(){
  19. $("p:last").removeClass("highlightpink");
  20. $("p:last").addClass("highlightyellow");
  21. });
  22. $("button#button2").click(function(){
  23. $("p:last").removeClass("highlightyellow");
  24. $("p:last").addClass("highlightpink");
  25. });
  26.  
  27. </script>
  28. </body>
  29. </html>




You may like to try this example here.

See how you can now dynamically change the class.

Notice that the two statements


$("p:last").removeClass("highlightpink"); 
$("p:last").addClass("highlightyellow");

can be combined to a single line

$("p:last").removeClass("highlightpink").addClass("highlightyellow");