Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Setting multiple attributes for an element at once with JavaScript

Writer Matthew Martinez

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", "");
elem.setAttribute("height", "100%");
elem.setAttribute("width", "100%");
2

14 Answers

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": "", "height": "100%", ...});
6

You might be able to use Object.assign(...) to apply your properties to the created element. Although some "properties (elem.height etc.) are read-only, i.e. accessors with only a getter (undefined setter)."

Keep in mind that height and width attributes are defined in pixels, not percents. You'll have to use CSS to make it fluid.

var elem = document.createElement('img')
Object.assign(elem, { className: 'my-image-class', src: ' height: 120, // pixels width: 160, // pixels onclick: function () { alert('Clicked!') }
})
document.body.appendChild(elem)
// One-liner:
// document.body.appendChild(Object.assign(document.createElement(...), {...}))
.my-image-class { height: 100%; width: 100%; border: solid 5px transparent; box-sizing: border-box
}
.my-image-class:hover { cursor: pointer; border-color: red
}
body { margin:0 }
7

If you wanted a framework-esq syntax (Note: IE 8+ support only), you could extend the Element prototype and add your own setAttributes function:

Element.prototype.setAttributes = function (attrs) { for (var idx in attrs) { if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object') { for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];} } else if (idx === 'html') { this.innerHTML = attrs[idx]; } else { this.setAttribute(idx, attrs[idx]); } }
};

This lets you use syntax like this:

var d = document.createElement('div');
d.setAttributes({ 'id':'my_div', 'class':'my_class', 'styles':{ 'backgroundColor':'blue', 'color':'red' }, 'html':'lol'
});

Try it:

If you don't like extending a host object (some are opposed) or need to support IE7-, just use it as a function

Note that setAttribute will not work for style in IE, or event handlers (you shouldn't anyway). The code above handles style, but not events.

Documentation

  • Object prototypes on MDN -
  • setAttribute on MDN -
12

You could code an ES5.1 helper function:

function setAttributes(el, attrs) { Object.keys(attrs).forEach(key => el.setAttribute(key, attrs[key]));
}

Call it like this:

setAttributes(elem, { src: ' height: '100%' });

You can create a function that takes a variable number of arguments:

function setAttributes(elem /* attribute, value pairs go here */) { for (var i = 1; i < arguments.length; i+=2) { elem.setAttribute(arguments[i], arguments[i+1]); }
}
setAttributes(elem, "src", "", "height", "100%", "width", "100%");

Or, you pass the attribute/value pairs in on an object:

 function setAttributes(elem, obj) { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { elem[prop] = obj[prop]; } } }
setAttributes(elem, { src: "", height: "100%", width: "100%"
});

You could also make your own chainable object wrapper/method:

function $$(elem) { return(new $$.init(elem));
}
$$.init = function(elem) { if (typeof elem === "string") { elem = document.getElementById(elem); } this.elem = elem;
}
$$.init.prototype = { set: function(prop, value) { this.elem[prop] = value; return(this); }
};
$$(elem).set("src", "").set("height", "100%").set("width", "100%");

Working example:

const setAttributes = (el, attrs) => Object.entries(attrs) .forEach(args => el.setAttribute(...args))

Or create a function that creates an element including attributes from parameters

function elemCreate(elType){ var element = document.createElement(elType); if (arguments.length>1){ var props = [].slice.call(arguments,1), key = props.shift(); while (key){ element.setAttribute(key,props.shift()); key = props.shift(); } } return element;
}
// usage
var img = elemCreate('img', 'width','100', 'height','100', 'src',');

FYI: height/width='100%' would not work using attributes. For a height/width of 100% you need the elements

6

Try this

function setAttribs(elm, ob) { //var r = []; //var i = 0; for (var z in ob) { if (ob.hasOwnProperty(z)) { try { elm[z] = ob[z]; } catch (er) { elm.setAttribute(z, ob[z]); } } } return elm;
}

DEMO: HERE

you can simply add a method (setAttributes, with "s" at the end) to "Element" prototype like:

Element.prototype.setAttributes = function(obj){ for(var prop in obj) { this.setAttribute(prop, obj[prop]) }
}

you can define it in one line:

Element.prototype.setAttributes = function(obj){ for(var prop in obj) this.setAttribute(prop, obj[prop]) }

and you can call it normally as you call the other methods. The attributes are given as an object:

elem.setAttributes({"src": "", "height": "100%", "width": "100%"})

you can add an if statement to throw an error if the given argument is not an object.

1

No function example:

let checkbox = document.createElement('input');
for (const [key, value] of Object.entries({ type: 'checkbox', id: 'sys-surname', class: 'switcher23', value: 1, name: 'surname' })) { checkbox.setAttribute(key, value); }
let elem = document.createElement("img");
Object.entries({"src": ""), "height": "100%", "width": "100%"}).forEach(kv => elem.setAttribute(kv[0], kv[1]));

use this function to create and set attributes at the same time

function createNode(node, attributes){ const el = document.createElement(node); for(let key in attributes){ el.setAttribute(key, attributes[key]); } return el;
}

use it like so

const input = createNode('input', { name: 'test', type: 'text', placeholder: 'Test'
});
document.body.appendChild(input);

I guess it's best way to set attributes at once for any element in this class.

function SetAtt(elements, attributes) { for (var element = 0; element < elements.length; element++) { for (var attribute = 0; attribute < attributes.length; attribute += 2) { elements[element].setAttribute(attributes[attribute], attributes[attribute + 1]); } }
}
var Class = document.getElementsByClassName("ClassName"); // class array list
var Data = ['att1', 'val1', 'att2', 'val2', 'att3', 'val3']; //attributes array list
SetAtt(Class, Data);

That's an easy way

let div = document.getElementsByTagName("div")[0];
let attr = ["class", "id", "title"];
let attrVlu = ["ahmed", "mohamed", "ashraf"];
for(let i = 0; i < 3; i++) { div.setAttribute(attr[i], attrVlu[i]);
}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy