- `index` - The index position of the element in the set.
- `currentclass` - The current class name(s) of the selected element.
` element when a button is clicked. ```javascript $("button").click(function(){ $("p:first").addClass("intro"); }); ``` ### Example 2: Add Multiple Classes You can add multiple classes at once by separating each class name with a space. ```javascript $("button").click(function(){ // Adds both "intro" and "highlight" classes to all
elements $("p").addClass("intro highlight"); }); ``` ### Example 3: Using a Callback Function You can dynamically determine which class to add by passing a function. This function receives the index of the element in the jQuery collection and its current class list as arguments. ```javascript $("button").click(function(){ $("li").addClass(function(index, currentclass){ // Adds the class "list-item-0", "list-item-1", etc., based on index return "list-item-" + index; }); }); ``` ### Example 4: Switching Classes (Combining addClass and removeClass) To replace an old class with a new one, you can chain the `removeClass()` and `addClass()` methods together. ```javascript $("button").click(function(){ // Removes the "old-style" class and adds the "new-style" class $("p").removeClass("old-style").addClass("new-style"); }); ``` --- ## Considerations & Best Practices 1. **No Duplicates:** If the specified class name is already assigned to the selected element, jQuery is smart enough not to duplicate it. 2. **No Dot Prefix:** When passing class names to `addClass()`, do not include the leading dot (`.`) that is used in CSS selectors. Pass `"my-class"`, not `".my-class"`. 3. **Chaining:** Like most jQuery methods, `addClass()` returns the jQuery object, allowing you to chain other jQuery methods immediately after it (e.g., `$("p").addClass("active").show();`).
YouTip