2023 Update
Don't use this as an extension to Element.prototype. In 2012, it was debatable practice. In 2023, the debate is settled: it's not the way to go about things. Manipulating the prototype of library-external classes has risks that are difficult or impossible to mitigate; this is an ugly tool. I tried to note that, but was apparently not emphatic enough.
However, you can read the internal approach of the method and write it as a function, it would work the same. I might use something like this:
const setAttributes = (el, attrs) =>
Object.keys(attrs)
.filter(key => el[key] !== undefined)
.forEach(key =>
typeof attrs[key] === 'object'
? Object.keys(attrs[key])
.forEach(innerKey => el[key][innerKey] = attrs[key][innerKey])
: el[key] = attrs[key]
);
http://jsfiddle.net/uL8tm603/46/
Original 2012 answer follows
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.assign()is worth a look for those that don't want to create a helper function - works for "all enumerable and own properties".