Description:
The Jquery addClass() method add the specified class(s) ย for the matched/selected elements.ย If we need to add more than one class then we need to use Space as the separate between the class names.ย It does not remove existing class attributes in the element, it only adds one or more class names to them.
Syntax
.addClass( className )
.addClass( function )
classNameย | It specify the class name to add for the selected element. More than one class will be included by using the space as separator. |
functionย | A function returning one or more space-separated class names to be added to the existing class name.ย The function accept two arguments as parameter, one is the index position of the element and ย second is the existing class name.ย |
Note :
To set multipleย class(s)
.addClass({“className1 className2”});
Example:ย
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 |
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function () { $("#divAdd").click(function () { $("#divBox").css("background-color", ""); $("#divBox").addClass("selected"); }); }); </script> <style type="text/css"> .selected { background-color: #ff6a00; } </style> </head> <body> <button style="margin: 20px;" id="divAdd">Add CSS Class</button> <div id="divBox" style="margin: 20px;width: 80px;height: 80px;left: 10px;top: 10px; background-color:#4CAF50"></div> </body> </html> |
Output:ย
Before clicking the buttonย “Add CSS Class” button
After clicking the “Add CSS Class” button, the “selected” class has appended to the divย and back-ground colorย has updated from the new class as shown below.
Note:
Here is the sample code for using Function as parameter.
$( “div” ).addClass(function( index, currentClass ) {// perform actionย based on the index/current Class name});
Leave A Comment