jQuery addClass() Method
The addClass() method in jQuery is used to add one or more class named to the selected elements.
This method does not delete any existing class attributes; it simply appends one or more class names to the class attribute.
Note: If we want to add more than one class to an element, we need to seperate the class names with spaces.
Syntax
Following is the syntax of addClass() method in jQuery −
$(selector).addClass(classname,function(index,currentclass))
Parameters
This method accepts the following parameters −
- classname: This specifies the name of the class(es) to be added to the selected element(s).
- function(index, currentclass): This is an optional callback function that allows you to manipulate each selected element individually.
Example 1
In the following example, we are using the addClass() method to add a class name "highlight" to all the <p> elements −
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").addClass("highlight");
})
});
</script>
</head>
<body>
<p>This paragraph will be highlighted.</p>
<p>This paragraph will also be highlighted.</p>
<button>Click</button>
</body>
</html>
When we click the button, the class "highlight" will be added to all the paragraph elements.
Example 2
In this example, we are adding multiple classes "highlight" and "bold" to the selected elements (<p>) −
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
.bold {
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").addClass("highlight bold");
})
});
</script>
</head>
<body>
<p>This paragraph will be highlighted and bold.</p>
<p>This paragraph will also be highlighted and bold.</p>
<button>Click</button>
</body>
</html>
After clicking the button, the class "highlight" and "bold will be added to all the paragraph elements.
Example 3
In this example, we use the addClass() method with a callback function to add different classes based on the index of each
element −
<html>
<head>
<style>
.even {
background-color: lightblue;
}
.odd {
background-color: lightgreen;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").addClass(function(index) {
return index % 2 === 0 ? "even" : "odd";
});
})
});
</script>
</head>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<button>Click</button>
</body>
</html>
When we click the button, the even indexed <p> elements will be highlighted with "lightblue" background color. Odd indexed <p> elements will be highlighted with "lightgreen" background color.