Skip to main content

How to Set Multiple Attributes on an Element in JavaScript

When creating or configuring DOM elements, you often need to set multiple HTML attributes at once, such as id, class, style, and data-* attributes. While you could set them one by one, a more efficient and readable approach is to use a helper function to set them from a single object.

This guide will teach you how to create a reusable function to set multiple attributes on a single element. We will also cover the related task of applying attributes to multiple elements at once.

There is no native, single method like element.setAttributes({...}). The standard and most effective way to solve this is to create a simple helper function that iterates over an object of attributes and applies them to the element.

The Core Method: setAttribute() in a Loop

Problem: you have created a new element and need to set several attributes on it in a clean and organized way.

// Problem: How to set all of these attributes on `myButton` efficiently?
let myButton = document.createElement('button');
let attributesToSet = {
'type': 'button',
'class': 'btn btn-primary',
'disabled': '',
'data-action': 'submit'
};

Solution: this helper function takes an element and an object of attributes as arguments.

/**
* Sets multiple attributes on a DOM element.
* @param {Element} element The element to set attributes on.
* @param {object} attributes An object of attribute key-value pairs.
*/
function setAttributes(element, attributes) {
for (let key in attributes) {
element.setAttribute(key, attributes[key]);
}
}

// Example Usage:
let myButton = document.createElement('button');
myButton.textContent = 'Click Me';

let attributes = {
type: 'button',
class: 'btn btn-primary',
disabled: '', // If this attribute is specified, then button will be disabled!
};

setAttributes(myButton, attributes);
document.body.appendChild(myButton);

How the Helper Function Works

  1. function setAttributes(element, attributes): We define a function that accepts two arguments: the target element and an object where keys are attribute names and values are attribute values.
  2. for (let key in attributes): We use a for...in loop to iterate over each key in the attributes object.
  3. element.setAttribute(key, attributes[key]): For each key, we call the standard setAttribute() method on the element.
    • The first argument is the attribute name (the key from our object).
    • The second argument is the attribute value (the value associated with that key in our object).

This pattern is a simple and powerful way to keep your DOM manipulation code clean and organized.

Setting an Attribute on Multiple Elements

If you need to apply the same attribute to multiple elements, the process is slightly different.

Logic:

  1. Select all the target elements using document.querySelectorAll().
  2. Iterate over the resulting NodeList with forEach().
  3. Call setAttribute() on each element inside the loop.

Solution: this example adds a title attribute to every element with the class box.

<div class="box">Box 1</div>
<div class="box">Box 2</div>
let boxes = document.querySelectorAll('.box');

boxes.forEach(box => {
box.setAttribute('title', 'This is a box element');
});

You can use the same iterative approach to remove multiple attributes from an element.

Solution: this helper function takes an element and an array of attribute names to remove.

function removeAttributes(element, ...attrs) {
for (let attr of attrs) {
element.removeAttribute(attr);
}
}

// Example Usage:
let myElement = document.getElementById('my-element');
removeAttributes(myElement, 'style', 'title', 'data-temp');
note

This function uses rest parameters (...attrs) to accept a flexible number of attribute names.

Conclusion

While JavaScript does not provide a single method for bulk attribute manipulation, the process is simple to implement with a loop.

  • To set multiple attributes on a single element, the recommended best practice is to create a helper function that iterates over an object of attributes and applies them with setAttribute().
  • To set an attribute on multiple elements, select the elements with querySelectorAll() and then iterate over the NodeList with forEach(), calling setAttribute() on each element.

By creating a reusable setAttributes helper function, you can make your DOM manipulation code cleaner, more readable, and more efficient.