Details NodeList and HTMLCollection and Array

  html, html5, javascript

Array, NodeList and HTMLCollection are three concepts and their relationship has many. The students who have been working in the front end for several years are not clear about them. They often meet them, but they feel very strange. They still feel confused when they are not cut. Today, let’s sort out these three things.

Almost everyone can understand Array, but the relationship among HTMLCollectio, NodeList and Array always seems ambiguous, a little bit like but not so like. It may be that I am stupid, but I am really getting a headache from them, so I must understand them today.

Let’s first look at what these three things look like regardless of so many concepts and definitions. Let’s create an html file and put three nested divs in it:

<!  DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 </head>
 <body>
 <div class="test-div">
 div1
 <div class="test-div">
 div2
 <div class="test-div">
 div3
 </div>
 </div>
 </div>
 </body>
 </html>

NodeList

First let’s look at NodeList, open the html file in the browser, open the console and enter:

document.querySelectorAll('div')
Print results

image

We found that the NodeList returned contains these three divs. Expand NodeList’s__proto__Property, NodeList inherits from a NodeList Object, which in turn inherits from an Object object.

NodeListlengthThere are 5 other method besides the attribute, namelyentries, forEach, item, keys, valuesWhat are these five methods used for? Use it again to know:

entries():

Calling the entries method returns an iterator (iterator). See for iterator/iterableMDNTo put it simply, it returns an object that can be traversed, and this object implements iterable protocal, so it needs to usefor...ofTraversal, so we can:

var divs = document.querySelectorAll('div');
 for(var item of divs.entries()){
 console.log(item);
 }

The result returned three arrays containing three div objects (why not three key-value pair? ), as shown in figure:

image

forEach():

ForEach is used in the same way as Array is used for traversing collection elements:

var divs = document.querySelectorAll('div');
 divs.forEach(function (el, index, list) {
 console.log(el);
 });
item():

item()Used to get a single node element from NodeList:

var divs = document.querySelectorAll('div');
 console.log(divs.item(0));

Print results:
image

keys():

Returns a key used by iterator to traverse NodeList:

var divs = document.querySelectorAll('div');
for (var key of list.keys()) {
console.log(key);
}

Print results:
image

values():

Andkeys()Similarly, an iterator is returned to traverse NodeList’s value, which is an html element:

var divs = document.querySelectorAll('div');
for (var value of divs.values()) {
console.log(value);
}

Print results:
image

Through the study of NodeList, we found that NodeList and Array have no inheritance relationship, but both havelengthAttributes andforEachMethod, and has several unique methods, are mainly used to traverse and value.

HTMLCollection

After knowing NodeList, let’s take a look at HTMLCollection again. Similarly, we first get an HTMLCollection and enter and execute it in the console:

document.getElementsByTagName('div')

Print results:

image

You can see that the resulting HTMLCollection inherits from an HTMLCollection Object, and HTMLCollection directly inherits from the object object, so it is level with NodeList. HTMLCollection, like NodeList, contains the html elements obtained from the query.lengthAttributes anditemMethod, but there is no NodeList’sentries, forEach, keys, valuesThese four methods, but one morenamedItem(filter elements by id and name) method …

Seeing the true features of NodeList and HTMLCollection, we are very curious how these two similar and independent guys were invented. Under what circumstances are NodeList obtained and HTMLCollection obtained?

This is how HTMLCollection is introduced on MDN:

Note: This interface is called HTMLCollection for historical reasons (before the modern DOM, collections implementing this interface could only have HTML elements as their items).

Translation is:
It is called HTMLCollection because of some historical reasons. before the emergence of the new generation DOM, the collection implementing HTMLCollection only contained HTML elements, so it was named HTMLCollection.

We know that DOM nodes include not only html elements, but also text node and comment. Since HTMLCollection only includes HTML elements, will NodeList include all types of DOM nodes? Let’s test it and write a paragraph of HTML first:

<div class="parent">
 this is patent content
 <div class="child">
 this is child content
 </div>
 <!  -- this is comment -->
 </div>

Then execute:

var parent = document.querySelector('.parent');
 console.log(parent.childNodes);

Print results:

image

We seechildNodesReturns all DOM nodes below the first div, including 3 textnodes (two of which are newline characters), a child div, and a comment. This confirms our conjecture about NodeList.

Let’s look at HTMLCollection again and execute:

var parent = document.querySelector('.parent');
console.log(parent.children);

Print results:

image

Only the child div is included, which also verifies the statement on MDN.

As for parent, what about childNodes and children?

Because parent is a Node object (with childNodes attribute) and because it has child elements, it is also a ParentNode object (with children attribute).

At this point, we should have a more comprehensive understanding of NodeList and HTMLCollection. to sum up, HTMLCollection is a relatively early model, which can only contain HTML elements. early interfaces such asdocument.getElementsByClassName,document.getElementsByTagNameThe return is HTMLCollection. NodeList is a relatively new model, which is more perfect than HTMLCollection. It has not only HTML elements, but also text nodes and comment. More recent interfaces such asdocument.querySelectorAllNodeList was returned.

Regarding NodeList, the relationship between HTMLCollection and Array is that they look alike and have some similar functions, but they are completely different things.

Of course, the stories about HTMLCollection and NodeList have not been finished, because they are sometimes live? Dynamic? Sometimes it is not live. Static? ), on this topic, later articles will be analyzed in detail.