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).
O(n) because the DOM tree lookup will be performed every time.
How to iterate a node list?
Iterating over Node Lists
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
It is better to do this instead:
However, you should be careful when using Google’s for-loop if you are creating
new DOM elements and adding them to the
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,
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
I recommend using the following for-loop, which I always use. It prevents infinite loop and is fast as well.