Możesz utworzyć funkcję, która przyjmuje zmienną liczbę argumentów:
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%");
Lub przekazujesz pary atrybut / wartość w obiekcie:
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%"
});
Możesz także stworzyć własne opakowanie / metodę obiektu z możliwością łączenia w łańcuch:
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%");
Przykład roboczy: http://jsfiddle.net/jfriend00/qncEz/
Object.assign()jest warta poszukania dla tych, którzy nie chcą tworzyć funkcji pomocniczej - działa dla „wszystkich wyliczalnych i własnych właściwości”.