How to Set Multiple Attributes for an Element in JavaScript

Migel Hewage Nimesha Feb 02, 2024
How to Set Multiple Attributes for an Element in JavaScript

This article uses the forEach method and for loop to illustrate how to set multiple attributes simultaneously for an element in JavaScript.

For that, we will also use HTML to ease our code and some JavaScript methods such as Object.keys() and getElementByID() as the helpers for the code.

In JavaScript, the setAttribute() method sets single or multiple attributes for an element. It has two parameters: name and value.

The name is the name of the new attribute. The value is the value of the new attribute. This method will create a new attribute and assign it a value. If that attribute exists, the new value will get updated.

To set a single attribute, we can use the below syntax.

element.setAttribute(name, value);

But to set multiple attributes, we can use this syntax several times, which is not a best practice. Instead of using it several times, we can use loops.

Use the for Loop to Set Multiple Attributes for an Element in JavaScript

First, we will create an input box using HTML. Then we will define a function in JavaScript that has two arguments. Finally, we will use a for loop to set multiple attributes inside it. First, let’s create our input box.

Example Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <!-- creating an input box with the id of 'inputBox' -->
    <input id="inputBox" type="text">
    
    <!-- importing the JavaScript file -->
    <script src="main.js"></script>
</body>
</html>

We can see an empty input box below as an output.

Output:

set multiple attributes for an element in javascript - empty input box

Now let’s set some attributes to our input box. First, let’s define our function as setMultipleAttributes().

function setMultipleAttributes(elmnt, attributesToSet) {}

Here we have defined two parameters for the function: elmnt and attributesToSet. elmnt is the element that you want to set the attributes. The attributesToSet are the attributes that you need to assign to the elmnt.

When we call the function, we should give an argument for each parameter. Now we can create our loop inside the function.

for (let i in attributesToSet) {
  elmnt.setAttribute(i, attributesToSet[i]);
}

Through this loop, all the arguments given to the attribute’s parameters will be set to the element one by one as attributes.

Our goal is to set attributes for the input element so let’s define a variable called inputB. Then we use getElementByID() method to access the input element.

Finally, we assign the inputB variable to the getElementByID() method so we can use that variable when calling the function.

const inputB = document.getElementById('inputBox');

Now let’s call the function. As arguments, we can add some attributes and values for them. Here we have added placeholder and disabled as attributes.

setMultipleAttributes(inputB, {'placeholder': 'Enter a word', 'disabled': ''});

Full JavaScript Code:

// A function to set multiple attributes.
// elmnt is the element.
// attributesToSet is/are the attribute(s).
function setMultipleAttributes(elmnt, attributesToSet) {
  // for loop along with setAttribute() method.
  for (let i in attributesToSet) {
    elmnt.setAttribute(i, attributesToSet[i]);
  }
}
// variable declaration and using getElementByID() method.
const inputB = document.getElementById('inputBox');

// Calling the function.
setMultipleAttributes(inputB, {'placeholder': 'Enter a word', 'disabled': ''});

Output (disabled input box which has a text as a placeholder):

set multiple attributes for an element in javascript - disabled input box

Use the forEach() Method to Set Multiple Attributes for an Element in JavaScript

Another way of setting multiple attributes for an element is to use the forEach() method. For this method, we will create a button using HTML and then set multiple attributes such as disabled, color, etc.

We will use an object and some methods such as forEach() and Object.keys() to achieve this. In the earlier method, we set attributes using arguments.

But in this method, we will store the attribute’s names and values in an object. Then, we can set those attributes for the button element using the above two methods.

First, let’s create a button using HTML as follows.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <!-- creating a button with the id of 'sampleButton' -->
    <button id="sampleButton">Click Here</button>
    
    <!-- importing the JavaScript file -->
    <script src="main.js"></script>
</body>
</html>

Output:

set multiple attributes for an element in javascript - create button

Here we create an object called eleAttributes; then, we can assign some attribute names and values as its properties.

const eleAttributes = {
  disabled: '',
  style: 'color:white; background-color:blue;',
};

As before, we can create a function for this method too. We can use this function to set the attributes stored in the object for the button element. First, let’s define the function as setMultipleAttributes().

function setMultipleAttributes(elmnt, attributesToSet) {

Here we have defined two parameters: elmnt and attributesToSet, to take as arguments by the user. So now we can create our loop inside of it. But, first, we need to create an array of attribute names.

Then through the loop, we can set the attributes one by one. Since all the attributes are inside the object, we use Object.keys() to create the array.

And along with that, we use the forEach() method for the iteration. Then, inside it, we use the setAttribute() method to assign those to the element.

Object.keys(eleAttributes).forEach(i => {
  elmnt.setAttribute(i, eleAttributes[i]);
});

Now we need to declare a variable and assign it to the getElementByID() method.

const button = document.getElementById('sampleButton');

Finally, we can call the function below.

setMultipleAttributes(button, eleAttributes);

Now we have completed the code. The full JavaScript code should look as follows.

// Creating an object called 'eleAttributes'.
const eleAttributes = {
  // add attributes as object properties.
  disabled: '',
  style: 'color:white; background-color:blue;',
};

// A function to set multiple attributes.
// elmnt is the element.
// attributesToSet is/are the attribute(s).
function setMultipleAttributes(elmnt, attributesToSet) {
  // creating an array of attribute names and using forEach() method for
  // iteration.
  Object.keys(eleAttributes).forEach(i => {
    // setting attributes one by one
    elmnt.setAttribute(i, eleAttributes[i]);
  });
}
// variable declaration and using getElementByID() method.
const button = document.getElementById('sampleButton');

// Calling the function.
setMultipleAttributes(button, eleAttributes);

Output (disabled button with changed colors):

set multiple attributes for an element in javascript - disabled button with blue color

As we have learned that we can accomplish it using the for loop and forEach() method. Through the for loop, we can apply attributes using arguments. In the forEach() method, we assign attributes to an object and using Object.keys(), we can set them for an element.

Migel Hewage Nimesha avatar Migel Hewage Nimesha avatar

Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.

Related Article - JavaScript Attribute