Skip to content
Advertisement

Setting multiple attributes for an element at once with JavaScript

How can I set multiple attributes at once with JavaScript? Unfortunately, I’m not able to use a framework like jQuery on this project. Here is what I have now:

var elem = document.createElement("img");

elem.setAttribute("src", "http://example.com/something.jpeg");
elem.setAttribute("height", "100%");
elem.setAttribute("width", "100%");

Advertisement

Answer

You could make a helper function:

function setAttributes(el, attrs) {
  for(var key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
}

Call it like this:

setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement