The DOM usually returns a NodeList for most operations, such as getElementsByTagName .
Although NodeList almost like an array, it is not. It has a length property, similar to an array, and an item(index) method for accessing an object at the specified index (also available using the [index] notation), but the one where the similarity ends.
So, to use the wonderful array methods without rewriting them all for NodeList , the above line is useful.
Another use of conversion to array is to make the list static. NodeLists usually live, which means that when a document changes, the NodeList object is automatically updated. This can cause problems if the jQuery object returned to you is constantly changing right under your nose. Try running the snippet to test the functionality of NodeLists.
var p = document.getElementsByTagName('p'); console.log(p.length); // 2 document.body.appendChild(document.createElement('p')); // length of p changes as document was modified console.log(p.length); // 3
Anurag Feb 28 '11 at 17:13 2011-02-28 17:13
source share