Add attribute to multiple Elements using JavaScript

avatar

Borislav Hadzhiev

Thu Dec 30 20212 min read

banner

Photo by Anonymous

Add attribute to multiple Elements using JavaScript #

To add a class to multiple elements:

  1. Select the elements using the document.querySelectorAll() method.
  2. Use a forEach method to iterate over the collection of elements.
  3. Use the setAttribute method to add an attribute to each element.

Here is the HTML for this example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const boxes = document.querySelectorAll('.box'); boxes.forEach((box, index) => { box.setAttribute('id', `box-${index}`); });

We used the document.querySelectorAll method to select all elements with a class of box.

We used the NodeList.forEach method to iterate over the NodeList.

To add an attribute to each element, we used the setAttribute method.

The setAttribute method takes 2 parameters:

  1. name - the name of the attribute whose value is to be set.
  2. value - the value to assign to the attribute.

In the example, we added an id attribute to each element in the NodeList.

If the attribute already exists, the value is updated, otherwise a new attribute is added with the specified name and value.

The querySelectorAll method takes one or more selectors, so we are able to select elements with multiple different classes, ids, tags, etc.

Here is an example that uses the method to get a collection of elements with 3 different classes.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box1">Box 1</div> <div class="box2">Box 2</div> <div class="box3">Box 3</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const boxes = document.querySelectorAll('.box1, .box2, .box3'); boxes.forEach((box, index) => { box.setAttribute('id', `box-${index}`); });

We passed 3 different selectors to the querySelectorAll method by separating them with commas.

You could pass an id to a method by prefixing the id value with a #, e.g. #my-id.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee