Setting multiple attributes for an element at once with JavaScript
JavascriptJavascript Problem Overview
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%");
Javascript Solutions
Solution 1 - Javascript
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%", ...});
Solution 2 - Javascript
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: 'https://dummyimage.com/320x240/ccc/fff.jpg',
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 }
Solution 3 - Javascript
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: http://jsfiddle.net/ywrXX/1/
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 - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/prototype
-
setAttribute
on MDN - https://developer.mozilla.org/en-US/docs/DOM/element.setAttribute
Solution 4 - Javascript
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: 'http://example.com/something.jpeg', height: '100%' });
Solution 5 - Javascript
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", "http://example.com/something.jpeg",
"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: "http://example.com/something.jpeg",
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", "http://example.com/something.jpeg").set("height", "100%").set("width", "100%");
Working example: http://jsfiddle.net/jfriend00/qncEz/
Solution 6 - Javascript
const setAttributes = (el, attrs) =>
Object.entries(attrs)
.forEach(args =>
el.setAttribute(...args))
Solution 7 - Javascript
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','http://example.com/something.jpeg');
FYI: height/width='100%'
would not work using attributes. For a height/width of 100% you need the elements style.height/style.width
Solution 8 - Javascript
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
Solution 9 - Javascript
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": "http://example.com/something.jpeg", "height": "100%", "width": "100%"})
you can add an if statement to throw an error if the given argument is not an object.
Solution 10 - Javascript
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);
}
Solution 11 - Javascript
let elem = document.createElement("img");
Object.entries({"src": "http://example.com/something.jpeg"),
"height": "100%",
"width": "100%"}).forEach(kv => elem.setAttribute(kv[0], kv[1]));
Solution 12 - Javascript
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);
Solution 13 - Javascript
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);
Solution 14 - Javascript
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]);
}