JavaScript Add Class to Multiple Elements


In this tutorial, we will explore how to add a class to multiple elements using JavaScript. Adding a class to multiple elements is a common task in web development, and it can be achieved using different approaches.

Let's see how to add a class to multiple elements using JavaScript.


Using a loop to iterate through elements

To add a class to multiple elements:

  1. Get all the elements to which you want to add a class.
  2. Iterate through the elements using a loop.
  3. Use the classList.add() method to add a class to each element.

Let's see an example of adding a class to multiple elements using a loop.

Example

<p>Para 1</p>
<p>Para 2</p>
<p>Para 3</p>

<script>
  let paras = document.querySelectorAll("p");

  for (let i = 0; i < paras.length; i++) {
    paras[i].classList.add("para");
  }
</script>

Utilizing getElementsByClassName() method

Another method to add a class to multiple elements is by using the getElementsByClassName() method. This method takes a class name as a parameter and returns a collection of elements with the given class.

We can then iterate over the collection and add a class to each element.

Example

<p class="big">Para 1</p>
<p class="big">Para 2</p>
<p class="big">Para 3</p>

<script>
  let paras = document.getElementsByClassName("big");

  for(var para of paras) {
    para.classList.add("para");
  }
</script>

Adding class to multiple different elements

To select multiple different elements, we can use the querySelectorAll() method. This method takes a CSS selector as a parameter and returns a collection of elements that match the selector.

Suppose a group of elements has a class para, some have a class big, and some have a class small. We can select all these elements using the querySelectorAll() method and add a class to each element.

Example

<p class="big">Para 1</p>
<p class="small">Para 2</p>
<p class="para">Para 3</p>

<script>
  let paras = document.querySelectorAll(".big, .small, .para");

  for(var para of paras) {
    para.classList.add("highlight");
  }
</script>

Conclusion

We learned how to use querySelectorAll with a for...of loop, getElementsByClassName, and forEach with querySelectorAll. These methods provide different ways to achieve the same result, allowing you to choose the one that suits your needs.