Difference between pseudo-array types in JavaScript
The difference between the two types of
pseudo-arrays is the different behavior when
changing DOM elements. Let, for example, we
obtained a collection of paragraphs in the
form of HTMLCollection and in the
form of NodeList. We will then create
and add another paragraph to our DOM. In this
case, it will automatically appear in
HTMLCollection, but the NodeList
collection will remain unchanged.
Let's look at an example. Let's have a div with paragraphs in it. Let's get our div and the same paragraphs as collections of two different types:
let parent = document.querySelector('div');
let elems1 = document.getElementsByTagName('p'); // HTMLCollection
let elems2 = document.querySelectorAll('p'); // NodeList
Let's add one more paragraph to our div:
let p = document.createElement('p');
parent.append(p);
As a result, one of the collections will change, and the second one will not:
console.log(elems1); // 4 paragraphs - with new one
console.log(elems2); // 3 original paragraphs
Check how the
children
property will behave when adding
a new element.
Check how the
childNodes
property will behave when adding
a new element.