Sometime we need to add multiple classes in jQuery. We can achieve it very simply by using jQuery addClass() method.
addClass( className ) : to Adds the specified class(es) to each of the set of matched elements.
Here className
Type: String
One or more space-separated classes to be added to the class attribute of each matched element.
.addClass( function(index, currentClass) )
function(index, currentClass)
Type: Function()
A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set.
Generally people add the class in an element like
1 2 3 4 5 6 7 8 | $(document).ready(function(){ $('.elementclass').addClass('test1'); //OR $('.elementclass').addClass('test1').addClass('test2'); } |
Adding more than one class at a time, separated by a space, to the set of matched elements, like :
1 2 3 4 5 6 7 | $(document).ready(function(){ $( "div" ).addClass( "Class1 Class2" ); $( "div" ).addClass( "Class1 Class2 class3 class4" ); }) |
There is one more way to add class using function in addClass() method
1 2 3 4 5 6 7 8 9 10 11 12 | <script> $( "div" ).addClass(function( index, class ) { var addedClass; if ( class === "blue" ) { addedClass = "yellow"; $( "p" ).text( "There is one yellow div" ); } return addedClass; }); </script> |
Note: addClass method does not replace a class. It simply append the class to already assigned to the elements.
If you have any problem in add multiple classes in jQuery. Please write to us your issue. We will try to resolve it as soon as possible.