Library foundation code

It should now be universally accepted that extending the DOM directly (via Element.prototype, Node.prototype etc.) is a bad idea. To combat the inherent problems with doing this, quite a few libraries (jQuery, BBC Glow, etc.) employ the “wrapper” technique which involves taking a bunch of DOM elements and stuffing them into an array-like object that inherits from a safely-extendible prototype.

If you want to have a go at creating your own jQuery-like DOM library, here’s something to get you started:

So far there's been 7 Responses to “Library foundation code”

Thanks for the post. It’s pretty informative for those who look under the hoods of libraries or like you said, those would would like to start something for themselves. Even though it’s just a foundation, I just wish you could of commented a little more to explain more of the what and why.

Looks like myWrapper is created through undeclared assignment instead of being declared properly. You must have missed it?

Converting nodelist to array with help of try-catch is a rather crude approach. We can do better than that, by feature testing at load-time if Array.prototype.slice/push can convert nodelist to array. If you care about performance, you can fork toArray (or whatever it’s called) method at load-time as well.

Something along these lines (untested, but hopefully shows the point):

@kangax, I’ve modified it as per your recommendations. It seems to work… I didn’t bother with canConvertNodelistToArray — I just assumed if it hasn’t thrown an exception within the try{} then I can continue to return the slice() function: