Document.querySelectorAll() method and the
Node.childNodes property both return a NodeList. But the former returns a static NodeList, while the latter returns a live NodeList. This is an important difference to understand, else your code might behave in unexpected ways.
Static NodeLists are unaffected by future changes to the DOM.
Imagine the following HTML…
3, which is what we’d expect, since there are three paragraph elements inside the NodeList.
Look what happens if we add another paragraph to the
Although there are now four paragraphs inside the
<body> element, the NodeList still contains only three. This is because static NodeLists do not pick up further changes to the DOM.
Live NodeLists are affected by further changes to the DOM.
Assume the same HTML as above:
Let’s save the
childNodes property to a variable, then log its length:
9 since there are four element nodes plus five whitespace nodes.
childNodes property considers all types of node including whitespace, comments, etc—not just HTML elements.)
But look what happens this time if we add another element:
There are now ten child nodes inside the
childNodes property returns a live NodeList, it gets updated automatically.
Even though I didn’t manually update the
childNodes variable, its
length property shows the updated number, which is
In practical terms
As they explain in the MDN Web Docs:
It's good to keep this distinction in mind when you choose how to iterate over the items in the
NodeList, and whether you should cache the list's
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!