How are objects like NodeList and HTMLCollection created? And do they have an advantage over arrays?
- Difference between HTMLCollection, NodeLists - Deonis
2 answers
NodeList and HTMLCollection are the interfaces provided by WebAPI for working with a collection of DOM elements.
The main difference between them is that in the NodeList collection there can be nodes of any type , while in the HTMLCollection collection only elements can be found.
Since these are interfaces, it is programmatically impossible to create them. They can only be obtained by calling the appropriate API functions, for example, getElementsByName , or as the field value of an object already received, for example, document.forms
An important feature of such collections is that they are usually alive . That is, any change in the DOM is immediately displayed in the collection.
var tests = document.getElementsByClassName('test'); console.log('tests.length:', tests.length); tests[0].className = 'without-test'; console.log('tests.length', tests.length); #container div::after { content: attr(class); } #container div { border: 1px solid red; } #container .test { border: 1px solid green; } <div id="container"> <div class="test"></div> <div class="test"></div> <div class="test"></div> <div class="test"></div> <div class="test"></div> </div> If we compare these collections with arrays, then they have not so much in common:
- presence of the length property
- the ability to access the item by index.
In the latest versions of some browsers, several methods have also been added to analogous array methods: forEach , entries , keys , values
Therefore, when traversing the entire collection, there is no particular difference if it is a collection or array.
But if you need to filter or change the collection, then you cannot do without an array.
These are just objects with some array methods for convenience.