27 May 2013,
On JavaScript, DOM, NodeList, and Array
How to iterate a node list
A node list is a live HTML collection of nodes. This means that changes on
the DOM tree are going to be reflected on the collection.
(If the NodeList is the return value of document.querySelectorAll, it is NOT live.)
Although we can iterate a node list and refer to its member like an array, it is not Array.
Refering to the node list is not O(1) (like Array).
It costs O(n) because the DOM tree lookup will be performed every time.
Node lists are often implemented as node iterators with a filter.
This means that getting a property like length is O(n), and
iterating over the list by re-checking the length will be O(n^2).
Running the above code will hang/crash your browser. As mentioned, the node
list is live (reflects DOM changes)! For every new p element created,
the paragraphs.length increases by 1. So you just created an infinite loop.
In such situation, it is better to convert the node list to a real array using
for loop or using Array.prototype.slice.call(paragraphs) first.
Last but not least, I created two jsperf comparisons 1
and 2 with several different for-loops.
I recommend using the following for-loop, which I always use. It prevents infinite loop and is fast as well.