Skip to main content

How to Add a Class to Multiple Elements in JavaScript

A common task in DOM manipulation is to apply a CSS class to a group of elements at once. You might need to highlight multiple rows in a table, change the style of several buttons, or show a set of hidden elements. While you can't add a class to multiple elements with a single command, the process is straightforward: first, you select all the target elements, and then you loop through them to add the class to each one individually.

This guide will teach you the standard, modern methods for selecting and iterating over multiple elements. You will learn the crucial difference between a NodeList and an HTMLCollection and see the best practices for using methods like querySelectorAll() and forEach() to write clean and efficient code.

The Two-Step Process: Select and Iterate

You cannot directly add a class to a collection of elements. The classList.add() method only works on a single element. Therefore, the process is always:

  1. Select: Use a DOM method like querySelectorAll() to get a collection (or list) of all the elements you want to modify.
  2. Iterate: Loop through this collection. In each iteration, you will have access to one element at a time, and you can then add the class to it.

Step 1: Selecting Multiple Elements

This is the most powerful and flexible method for selecting elements. It uses a CSS selector string, which allows you to select elements by class, ID, tag, attribute, or any combination.

The solution:

// This selects all <div> elements with the class "box"
const boxes = document.querySelectorAll('div.box');

// This selects elements with class "box1", "box2", or id "special-box"
const elements = document.querySelectorAll('.box1, .box2, #special-box');

querySelectorAll() returns a NodeList.

The getElementsByClassName() Method

This is a more specific method that selects all elements that have a given class name.

The Solution:

// This selects all elements with the class "box"
const boxes = document.getElementsByClassName('box');

getElementsByClassName() returns an HTMLCollection. The difference is important and is explained later.

Step 2: Iterating and Adding the Class

Once you have your collection of elements, you can loop through it to add the class.

If you selected your elements with querySelectorAll(), the resulting NodeList has a built-in forEach() method, which is the cleanest and most modern way to iterate.

Example of a problem: you have multiple div elements and want to add a bg-yellow class to all of them.

<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>

The Solution:

const boxes = document.querySelectorAll('.box');

// The forEach method calls the provided function once for each element.
boxes.forEach(box => {
box.classList.add('bg-yellow');
});
note

This is the recommended pattern for its readability and conciseness.

Using a for...of Loop

The for...of loop is another excellent and highly readable way to iterate over collections. It works on both NodeList (from querySelectorAll) and HTMLCollection (from getElementsByClassName) without any changes.

The Solution:

const boxes = document.querySelectorAll('.box');

for (const box of boxes) {
box.classList.add('bg-yellow');
}

Adding Multiple Classes at Once

The classList.add() method can accept multiple arguments, allowing you to add several classes to an element in a single call.

const boxes = document.querySelectorAll('.box');

boxes.forEach(box => {
// Add three different classes to each box
box.classList.add('bg-yellow', 'text-bold', 'p-4');
});

This is more efficient and readable than calling classList.add() multiple times inside the loop.

A Note on HTMLCollection vs. NodeList

This is a key technical difference that often confuses beginners.

  • NodeList (from querySelectorAll): Has a built-in forEach() method.
  • HTMLCollection (from getElementsByClassName): Does not have a forEach() method.

Example of error:

// This will FAIL with a TypeError!
const boxes = document.getElementsByClassName('box');
boxes.forEach(box => { ... }); // ⛔️ boxes.forEach is not a function

If you must use getElementsByClassName, you have two possible solutions:

  1. Use a for...of loop, which works on HTMLCollection.
  2. Convert the collection to an array first, then use forEach().
    const collection = document.getElementsByClassName('box');
    const boxesArray = Array.from(collection);

    boxesArray.forEach(box => {
    box.classList.add('bg-yellow');
    });
note

It is simpler to just use querySelectorAll() from the start.

Conclusion

Adding a class to multiple elements is a simple two-step process that is fundamental to dynamic web development.

  • Select your elements first. The querySelectorAll() method is recommended for its power and flexibility.
  • Iterate over the resulting collection. The forEach() method (available on NodeList) is the cleanest and most modern way to do this. A for...of loop is also an excellent and highly compatible choice.
  • Inside the loop, use element.classList.add('class1', 'class2') to add one or more classes.