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: 

<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

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.

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 Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.