English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The addClass() method adds one or more class names to the selected element.
This method will not delete the existing class attribute but will only add one or more class names to the class attribute.
Add class:
$(selector).addClass(className)
Use a function to add a class:
$(selector).addClass(function(index, currentClass))
Add a class name to the first <p> element:
$("button").click(function(){ $("p:first").addClass("highlight"); });Test See‹/›
Multiple classes (separated by spaces) can be added to the selected element at one time, as shown below:
$("button").click(function(){ $("p:first").addClass("highlight big"); });Test See‹/›
Use a function to add a class:
$("p").addClass(function(index, currentClass) { let addedClass; if(currentClass === "red") { addedClass = "green"; $(this).text("There is a green paragraph"); } return addedClass; });Test See‹/›
Use removeClass() to delete a class name and add a new class name with addClass():
$("button").click(function(){ $("p").removeClass("red").addClass("green"); });Test See‹/›
Parameter | Description |
---|---|
className | Specify one or more class names separated by spaces to be added |
function(index, currentClass) | Function that returns one or more space-separated class names to be added to the existing class names
|