SIMPLIFIED EXAMPLE CODE:
var $ = function(selector, node) { // Selector engine
var selector = selector.trim(), node = node || document.body;
if (selector != null) {
return Array.prototype.slice.call(node.querySelectorAll(selector), 0); }
}
}
I want to use it like this…:
$("div").innerHTML='It works!';
…not like this…:
$("div")[0].innerHTML='It works only on the specified index!';
…or this:
for(i=0;i<$('div');i++) {
$("div")[i].innerHTML='It works great but it's ugly!';
}
This is as close as I got. I would like chaining to work and for it to be compatible with native methods:
if(!Array.prototype.innerHTML) {
Array.prototype.innerHTML = function(html) {
for (var i = 0; i < this.length; i++) {
this[i].innerHTML = html;
}
}
}
$("div").innerHTML('It works, but it ruins method chaining!');
I decided to build this engine to better learn JavaScript; It’s working but I am hoping I can learn some more from the kind members of Stack Overflow. Any help would be much appreciated!
It sounds like you want to have assigning to
innerHTMLon your set of results assign to theinnerHTMLof all of the results.To do that, you’ll have to use a function, either directly or indirectly.
Directly:
There, we define a function, and we assign it to the array you’re returning as a property. You can then call that function on the array. (You might want to use
Object.definePropertyif it’s available to set thesetInnerHTMLproperty, so you can make it non-enumerable.)Indirectly (requires an ES5-enabled JavaScript engine):
There, we use
Object.definePropertyto define a setter for the property.In the comments below you say
To make chaining work, you do
return this;from each of the functions (so the end ofmakeClasswould doreturn this;). That’s because when you’re chaining, such asobj.foo().bar(), you’re callingbaron the return value offoo. So to make chaining work, you make surefooreturnsthis(the object on whichfoowas called).