In JavaScript any list of elements returned by a DOM method is returned as a NodeList object. The NodeList object is very similar to a standard array in a lot of ways, but different enough that they can throw you for a loop if you aren’t watching what you’re doing.
In this article I am going to cover a few of the important differences between NodeLists and Arrays and several methods for solving the problems they can create.
To access arrays in JavaScript we use the familiar C style index operator [], but because a NodeList is not an array this is not always reliable.
Tracking down bugs caused by accessing elements in a node array using their index can be difficult as they can be quite subtle. A best practice to avoid problems is to use the NodeList’s "item()" method instead.
node_list = document.getElementsByTagName("div");
// Incorrect code:
for( x = 0; x < node_list.length; x++)
{
// We should access the elements in a
// NodeList by index. This is incorrect:
alert( node_list[x].className );
}
// Correct code:
for( x = 0; x < node_list.length; x++)
{
alert( node_list.item(x).className );
}
Merging arrays in JavaScript is a wonderfully simple task, simply call one array’s "concat()" method with the other array as the parameter. Presto! Unfortunately the same cannot be said for merging two NodeList objects.
Because a NodeList is not an array it does not have a "concat()" method, JavaScript also unfortunately lacks a method to combine the properties of two objects. This means that there is no simple way to merge two NodeList objects.
Several of the more well known JavaScript libraries (including jQuery and Prototype) address this issue by adding a method to the NodeLists involved that allows merging, but I will not cover that here as they rely on functions that are not built into the DOM.