English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery addClass() Method

jQuery HTML/CSS Methods

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.

Syntax:

Add class:

$(selector).addClass(className)

Use a function to add a class:

$(selector).addClass(function(index, currentClass))

Example

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 Value

ParameterDescription
classNameSpecify 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
  • index-Return the index position of the element in the collection

  • currentClass-Return the current class name of the selected element

jQuery HTML/CSS Methods