Wednesday, September 26, 2012

Extend NodeList

I started to move away from jQuery. Plain old JS in new browsers now support css selectors to return dom elements, which was like 50% of the awesomeness that jQuery gave you in my opinion. I'm not sure if anyone out there is not using jQuery, so this probably pertains to no one.
So I started cranking out my own framework... I started changing the prototype of NodeList (which is the return type of the document.querySelectorAll method) and things were going great, until I had to create a NodeList object. new NodeList throws an error...
I figured I could get around this problem by extending NodeList. I did this with the following code:
var ElementList = function() {}
ElementList.prototype = document.querySelectorAll('doesntexist')

This works but it has two problems:

  1. as you add to the ElementList array, the length property doesn't get updated
  2. FF has a bug (new ElementList) instanceof NodeList == false
The way I get around 1 is by using a for in loop, and check to make sure the the property matches /^\d+$/. Then to get around the second one, I might file a bug report to FF, but in the mean time, I just check for ElementList inheritance along with NodeList inheritance.

UPDATE

I have since filed a bug with FF, and the issue has been fixed.

1 comment:

  1. Interesting. The oddest thing being that NodeList is not a constructor - even if you try "new nodeListSample.constructor()"...

    ReplyDelete