How to Add a CSS Class to an Element in jQuery
This article explains how to use jQuery to dynamically add CSS classes to HTML elements. You will learn about the primary jQuery method designed for this task, review its syntax, and see practical code examples demonstrating how to add single classes, multiple classes, or apply classes conditionally based on element index or existing attributes.
The addClass() Method
The primary jQuery method used to add a CSS class to an element is
.addClass(). This method appends one or more specified
class names to the class attribute of the matched elements
without removing any existing classes.
Basic Syntax
$(selector).addClass(className);selector: The HTML element(s) you want to target.className: One or more class names to add to the selected element(s).
Adding a Single Class
To add a single class to an element, pass the class name as a string
to .addClass(). Do not include the leading dot
(.) in the class name itself.
// Adds the class "highlight" to all <p> elements
$("p").addClass("highlight");Adding Multiple Classes
You can add multiple CSS classes at once by separating each class name with a space within the string argument.
// Adds both "highlight" and "border-active" classes to a specific div
$("#myDiv").addClass("highlight border-active");Adding Classes Using a Function
The .addClass() method also accepts a callback function
as an argument. This is useful when you want to compute class names
dynamically based on the element's index or its current classes.
$("li").addClass(function(index, currentClass) {
// Adds "item-0", "item-1", etc., to each <li> element
return "item-" + index;
});The function receives two parameters:
index: The zero-based index position of the element within the set.currentClass: The current class attribute of the element.
The value returned by the function is appended as a new class to that specific element.