Home/Jquery/addClass() method in Jquery

addClass() method in Jquery

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: 

Output: 

Before clicking the button Add CSS Class” button

dotnet-helpers-jquery-addclass-method-thiyagu-jquery-helpers

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.

dotnet-helpers-jquery-addclass-method-thiyagu-jquery-helpers-com-output

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