So, for fun, I decided to see if I could mimic the syntax/functionality of jQuery. This turned out to be fairly easy (when not worrying about cross-browser/legacy compatibility). You can see what I’ve done so far here: http://jsfiddle.net/FPAaM/3/
Now, in the interest of not stepping on the toes of other third-party javascript libraries, what concerns should be noted when adding functionality to the prototypes of Node and NodeList?
Node.prototype.text = function(txt){
var chld = this.childNodes;
while(chld[0]) this.removeChild(chld[0]);
this.appendChild(document.createTextNode(txt));
return this;
};
NodeList.prototype.text = function(txt){
for (var i = 0; i < this.length; i++)
this[i].text(txt);
return this;
};
Node.prototype.css = function(tag, val){
if (val != undefined)
this.style[tag] = val;
else
return this.style[tag];
return this;
};
NodeList.prototype.css = function(tag, val){
for (var i = 0; i < this.length; i++)
this[i].css(tag, val);
return this;
};
Node.prototype.clk = function(cbk){
this.addEventListener("click", cbk, false);
return this;
};
NodeList.prototype.clk = function(cbk){
for (var i = 0; i < this.length; i++)
this[i].clk(cbk);
return this;
};
var $ = function(args){
if (typeof args == "function")
document.addEventListener("DOMContentLoaded", args, false);
if (typeof args == "string")
return document.querySelectorAll(args);
return args;
};
$(function(){
$("div.fancy").text("Poor man's jQuery!")
.css("color", "red")
.clk(function(e){
if (this.css("color") == "red")
$(this).css("color", "green");
else
this.css("color", "red");
});
});
NodeandNodeListare host objects. You should not extend them. The better way is to use a wrapper (like jQuery).Check this: What’s wrong with extending the DOM