jQuery addClass()

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

jQuery addClass()

The addclass() method is used to add one or more class name to the selected element. This method is used only to add one or more class names to the class attributes not to remove the existing class attributes.

If you want to add more than one class separate the class names with spaces.

Syntax:

  1. $(selector).addClass(classname,function(index,oldclass))   

Parameters of jQuery addClass() method

Parameter Description
Classname It is a mandatory parameter. It specifies one or more class names which you want to add.
Function (index, currentclass) It is an optional parameter. It specifies a function that returns one or more class names to be added.
  • Index: It is used to provide the index position of the element in the set.
  • Currentclass: It is used to return the current class name of the selected element.

Example of jQuery addClass() method

Let?s take an example to demonstrate the effect of jQuery addclass() method:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  5. <script>  
  6. $(document).ready(function(){  
  7.     $("button").click(function(){  
  8.         $("p:first").addClass("intro");  
  9.     });  
  10. });  
  11. </script>  
  12. <style>  
  13. .intro {  
  14.     font-size: 200%;  
  15.     color: red;  
  16. }  
  17. </style>  
  18. </head>  
  19. <body>  
  20. <h1>This is a heading</h1>  
  21. <p>This is a paragraph.</p>  
  22. <p>This is another paragraph.</p>  
  23. <button>Add a class name to the first p element</button>  
  24. </body>  
  25. </html>  

Test it Now