Nodelists are not like arrays

October 17th, 2007 mikeb

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) {
    doSomethingWith(nodes[i]);
}

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.

Entry Filed under: Technology

3 Comments Add your own

  • 1. Tom Berger  |  October 17th, 2007 at 5:48 pm

    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. mikeb  |  October 17th, 2007 at 11:03 pm

    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. matthew  |  October 18th, 2007 at 9:35 am

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

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

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

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed

Calendar

October 2007
M T W T F S S
« Sep   Nov »
1234567
891011121314
15161718192021
22232425262728
293031  

Most Recent Posts