Nodelists are not like arrays

By: on October 17, 2007

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.

FacebookTwitterGoogle+

3 Comments

  1. Tom Berger says:

    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 says:

    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 says:

    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).

Post a comment

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>