technology from back to front

Nodelists are not like arrays

In JavaScript, it is possible to index into a DOM nodelist by using the square bracket notation:
var firstchild = node.childNodes[0];. But, despite Apple saying “[a] nodeList is equivalent to an array”, and the Mozilla guys saying “[a] nodeList is an array of elements”, a nodelist is not like an array.

It is tempting to use JavaScript’s for .. in syntax to iterate through a nodelist; e.g.,

var nodes = parent.childNodes;
for (var i in nodes) {

This won’t work: In Firefox, you get numbers, then ‘item’ and ‘length’, and with WebKit you get just ‘item’ and ‘length’. If a nodelist was like an array, this is really not what you’d expect!

But, it shouldn’t work, and in fact, Firefox gets this wrong. Looking at the specification for JavaScript DOM bindings, we can see that the NodeList interface has two properties, ‘length’ and ‘item’, and that the dereference using square brackets is just a misleading convenience.

  1. JS’s for … in notation is bong anyway. Whenever I try to use it I have to remind myself that it returns the keys and not the values. I always get it wrong the first time.

    I wonder how MochiKit’s iter module handles node lists (or other platform libraries’ equivalent, if they have something like that).

  2. MochiKit’s forEac() and map() certainly play nicely with nodelists — in fact I mostly use those, unless I need the keys as well, or to short-circuit.

  3. The issue with getting values or keys is solved, eg in lua, where you write:

    for (k, v) in pairs(t) do

    where t is a table (though pairs treats it as a map. Sorta).


− three = 0

2000-14 LShift Ltd, 1st Floor, Hoxton Point, 6 Rufus Street, London, N1 6PE, UK+44 (0)20 7729 7060   Contact us