Set multiple Attributes on an Element using JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 5, 2024
4 min

banner

# Table of Contents

  1. Set multiple Attributes on an Element using JavaScript
  2. Remove multiple attributes from an element
  3. Add attribute to multiple Elements using JavaScript

# Set multiple Attributes on an Element using JavaScript

To set multiple attributes at once on an element:

  1. Add the attribute names and values to an object.
  2. Use the Object.keys() method to get an array of the object's keys.
  3. Use the forEach() method to iterate over the array.
  4. Use the setAttribute() method to set each attribute on the element.

Here is the HTML for the examples.

index.html
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <button id="btn">Button 1</button> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
function setAttributes(element, attributes) { Object.keys(attributes).forEach(attr => { element.setAttribute(attr, attributes[attr]); }); } const attributes = { name: 'example', title: 'Box 1', disabled: '', style: 'background-color: salmon; color: white;', }; const button = document.getElementById('btn'); setAttributes(button, attributes);

set multiple attributes on element

The code for this article is available on GitHub

We created a reusable function that takes an element and an object of attribute names and values and adds them to the element.

We used the Object.keys() method to get an array of the attribute names.

index.js
const attributes = { name: 'example', title: 'Box 1', disabled: '', style: 'background-color: salmon; color: white;', }; // 👇️ ['name', 'title', 'disabled', 'style'] console.log(Object.keys(attributes));

The function we passed to the Array.forEach() method gets called with each element in the array.

On each iteration, we use the setAttribute() method to set an attribute on the element.

If the attribute already exists on the element, its value is updated. Otherwise, a new attribute is added with the specified name and value.

When you use the setAttribute method, you are setting or replacing attributes on the element.

For example, if the element already has a style attribute and you use the setAttribute method to update its style, you would replace the existing style with the provided value. The two values wouldn't get merged.

When setting the value of a boolean attribute, such as disabled, we can specify any value for the attribute and it will work.

If the attribute is present at all, regardless of the value, its value is considered to be true.

If a boolean attribute, such as disabled, is not present, the value of the attribute is considered to be false.

It is a best practice to set boolean attributes to an empty string. This sets the attribute on the element without a value.

If you need to remove an attribute from an element, use the removeAttribute() method.

index.js
const button = document.getElementById('btn'); button.removeAttribute('name');

# Remove multiple attributes from an element

If you need to remove multiple attributes from an element, you can use the same approach we used when adding multiple attributes.

This time things are a bit more straightforward. We only need the names of the attributes to be removed, so we can use an array instead of an object.

index.js
function removeAttributes(element, attributes) { attributes.forEach(attr => { element.removeAttribute(attr); }); } const attributes = ['name', 'title', 'disabled', 'style']; const button = document.getElementById('btn'); removeAttributes(button, attributes);

remove multiple attributes from element

The code for this article is available on GitHub

We stored the attribute names in an array and used the forEach() method to iterate over the array.

On each iteration, we use the removeAttribute() method to remove the attribute from the element.

# Add attribute to multiple Elements using JavaScript

To add an attribute 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" /> <title>bobbyhadz.com</title> </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>
The code for this article is available on GitHub

And here is the related JavaScript code.

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

add attribute to multiple elements

The code for this article is available on GitHub

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>
The code for this article is available on GitHub

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}`); });
The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.