Categories
JavaScript Answers

How to set multiple attributes for an element at once with JavaScript?

Spread the love

Sometimes, we want to set multiple attributes for an element at once with JavaScript.

In this article, we’ll look at how to set multiple attributes for an element at once with JavaScript.

How to set multiple attributes for an element at once with JavaScript?

To set multiple attributes for an element at once with JavaScript, we can call the element’s setAttribute method.

For instance, we write

const setAttributes = (el, attrs) => {
  for (const [key, val] of Object.entries(attrs)) {
    el.setAttribute(key, val);
  }
};

const attrs = {
  src: "http://example.com/something.jpeg",
  height: "100%",
  //...
};
setAttributes(elem, attrs);

to define the setAttributes function.

In it, we use a for-of loop to loop through each property that we get from Object.entries.

In the loop, we call el.setAttribute with key and val to set attribute with name key to val.

Then we call setAttributes with the elem element and the attrs object with the attributes we want to set.

Conclusion

To set multiple attributes for an element at once with JavaScript, we can call the element’s setAttribute method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *