jQuery addClass


The addClass adds a class to selected entity. The addClass does NOT replace a class but rather adds the class, appending it to any which may already be assigned to the elements.

It is possible to add more than one class separated by a space, to the set of matched elements.

Here is an example of the the addClass. It adds a CSS class name highlight which highllights the last paragraph when the buttun is clicked.

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




You may like to try this example here.

Exercises



1. Change the line number 18

$("p:last").addClass("highlight");

in the above example, so that the first paragraph in place of the last paragraph is selected. Check the solution here.

2. Change the line number 18

$("p:last").addClass("highlight");

in the above example, so that the all the three paragrahs in place of just the last paragraph is selected. Check the solution here.

3. In the above example add two buttons with ids button1 and button2 respectively. On pressing button with id button1, last line should get highlighted to yellow. When button 2 is pressed, the last line should get highlighted to pink. We do not require the highlighting to change dynamically. Check the solution here.

addClass does not replace a Class


If you have done the exercise 3 above carefully ( check the solution), you noticed that , it is not possible to change the highlighting dynamically. In order to change the class dynamically, the addClass is used in conjunction with removeClass method to replace a class. We will cover the removeClass method in the next post.