「.」で続けられるように

set系のメソッドはなどは何も返り値がないものが多いのですが、メソッドチェーンで書きたいときに不便なので返り値を返すようにします

今回は、Elementのメソッドです

Element.prototype.addAttr = function(an,av){
return this.setAttribute(an,av), this;
};
Element.prototype.addAttrs = function(){
var that = this;
Array.prototype.forEach.call(arguments,function(arg){
if(arg instanceof Array)
that.setAttribute(arg[0], arg[1]);
else if(arg instanceof Object)
arg.forIn(function(key,val){that.setAttribute(key,val)});
});
return this;
};
Element.prototype.addProp = function(p,v){
this[p] = v;
return this;
};
Element.prototype.addProps = function(){
var that = this;
Array.prototype.forEach.call(arguments,function(arg){
if(arg instanceof Array)
that[arg[0]] = arg[1];
else if(arg instanceof Object)
arg.forIn(function(key,val){that[key] = val});
});
return this;
};
Element.prototype.appendChilds = function(){
var that = this;
Array.prototype.forEach.call(arguments,function(arg){that.appendChild(arg)});
return this;
}; Object.prototype.forIn = function(func){ if(typeof func != "function") return false; for(var key in this){ if(this.hasOwnProperty(key)){ func(key,this[key],this); } } return this; };
これをすることで、
var elem = document.createElement("input");
elem.className = "class_A";
elem.type = "range";
elem.min = -100;
elem.max = 100;
elem.value = 0;
var a1 = elem.cloneNode(true);
a1.id = "A1";
var a2 = elem.cloneNode(true);
a2.id = "A2";
var a3 = elem.cloneNode(true);
a3.id = "A3";
var a4 = elem.cloneNode(true);
a4.id = "A4";
var parent = document.getElementById("A");
parent.appendChild(a1);
parent.appendChild(a2);
parent.appendChild(a3);
parent.appendChild(a4);
これが、
var elem = document.createElement("input").addAttrs({
class:"class_A",
type:"range",
min:-100,
max:100,
value:0,
});
document.getElementById("A").appendChilds(
elem.cloneNode(true).addAttr("id","A1"),
elem.cloneNode(true).addAttr("id","A2"),
elem.cloneNode(true).addAttr("id","A3"),
elem.cloneNode(true).addAttr("id","A4")
);
これだけですみます

書きやすいし見やすいです