Add Multiple CSS Classes at Once Using jQuery

Adding multiple CSS classes to an HTML element simultaneously is a common task in web development that can streamline DOM manipulation and styling workflows. In jQuery, this can be achieved cleanly and efficiently using the built-in .addClass() method by providing space-separated class names, passing a callback function for dynamic assignment, or chaining multiple method calls.

The most straightforward and widely used approach is to pass a single string containing all the class names separated by spaces directly into the .addClass() method.

// Syntax
$("#myElement").addClass("class1 class2 class3");

Example:

<div id="box">Content</div>

<script>
  $(document).ready(function() {
    $("#box").addClass("highlight rounded shadow-lg");
  });
</script>

When this code runs, jQuery adds highlight, rounded, and shadow-lg to the #box element without overwriting any existing classes already present on the element.


Method 2: Using an Array with .join()

If your classes are stored in an array or generated dynamically, you can convert the array into a space-separated string using JavaScript’s native .join(' ') method before passing it to .addClass().

const classList = ["primary-btn", "active", "fade-in"];

$("#submitButton").addClass(classList.join(" "));

This dynamically applies all elements in the array as distinct classes on the selected element.


Method 3: Using a Function for Dynamic Classes

The .addClass() method also accepts a function as an argument. The function receives the element's index and its current class list, returning a space-separated string of classes to add. This is useful when class addition depends on element state or index.

$("li").addClass(function(index, currentClass) {
  let classesToAdd = "list-item";
  if (index % 2 === 0) {
    classesToAdd += " even-row";
  }
  return classesToAdd;
});

Method 4: Method Chaining

While less concise than passing a space-separated string, you can chain multiple .addClass() calls together.

$("#myElement")
  .addClass("first-class")
  .addClass("second-class");

Passing a space-separated string remains the standard best practice for performance and readability.