Home > Web Front-end > JS Tutorial > Parsing of NodeList, HTMLCollection and Array

Parsing of NodeList, HTMLCollection and Array

不言
Release: 2018-07-07 17:30:44
Original
1978 people have browsed it

This article mainly introduces the analysis of NodeList, HTMLCollection and Array. It has certain reference value. Now I share it with you. Friends in need can refer to

Array, NodeList and HTMLCollection. Many students who have been doing front-end work for several years are not clear about concepts and their relationships. They often encounter them but feel unfamiliar, and they feel confused after being cut and sorted out. Today we will sort out these three things.

Everyone can almost understand Array, but the relationship between HTMLCollectio, NodeList and Array always seems to be very ambiguous. They are a little similar but not that similar. Maybe I am stupid, but I am really confused by them. It gives me a headache, so I decided to understand them today.

Let’s ignore so many concepts and definitions first, let’s take a look at what these three things look like. Let's first create an html file with three nested p's in it:

nbsp;html>


    <meta>
    <meta>
    <meta>
    <title>Document</title>


    <p>
        p1
        </p><p>
            p2
            </p><p>
                p3
            </p>
        
    

Copy after login

NodeList

First let's study NodeList, open this html file in the browser, and open the control Taiwan input:

document.querySelectorAll('p')
Copy after login
Print result

Parsing of NodeList, HTMLCollection and Array

We found that the returned NodeList contains these three p. After expanding the __proto__ attribute of NodeList, we found that NodeList inherits from a NodeList object, and this NodeList object inherits from the Object object.

In addition to the length attribute, NodeList has 5 other methods (methods), namely entries, forEach, item, keys, values. These five methods are What is it used for? Use it once and you will know:

entries():

Calling the entries method will return an iterator (iterator). For information about iterator/iterable, please refer to MDN. To put it simply, it returns an iterator that can be traversed object, and this object implements iterable protocol, so we need to use for...of to traverse, so we can:

var ps = document.querySelectorAll('p');
for(var item of ps.entries()){
    console.log(item);
}
Copy after login

The result returns three arrays containing three p objects ( Why not three key-value pairs?), as shown in the figure:

Parsing of NodeList, HTMLCollection and Array

forEach():

The usage of forEach is the same as the usage of Array’s forEach, both Is used to traverse collection elements:

var ps = document.querySelectorAll('p');
ps.forEach(function (el, index, list) {
    console.log(el);
});
Copy after login
item():

item() is used to obtain a single node element from NodeList:

var ps = document.querySelectorAll('p');
console.log(ps.item(0));
Copy after login

Print result:
Parsing of NodeList, HTMLCollection and Array

keys():

Returns an iterator for traversing the keys of NodeList:

var ps = document.querySelectorAll('p');
for (var key of list.keys()) {
    console.log(key);
}
Copy after login

Print result:
Parsing of NodeList, HTMLCollection and Array

values():

Similar to keys(), returns an iterator for traversing the value of NodeList, that is, html element:

var ps = document.querySelectorAll('p');
for (var value of ps.values()) {
    console.log(value);
}
Copy after login

Print result:
Parsing of NodeList, HTMLCollection and Array

Through the research on NodeList, we found that NodeList and Array have no inheritance relationship, but they both have the length attribute and the forEach method. , and has several unique methods, which are mainly used for traversing and obtaining values.

HTMLCollection

After getting to know NodeList, let’s get to know HTMLCollection again. Similarly, we first obtain an HTMLCollection, enter and execute it in the console:

document.getElementsByTagName('p')
Copy after login

Print result:

Parsing of NodeList, HTMLCollection and Array

You can see that the obtained HTMLCollection inherits from an HTMLCollection object, and HTMLCollection directly inherits from the Object object, so it is at the same level as NodeList. HTMLCollection, like NodeList, contains the html elements obtained from the query, length attributes and item methods, but does not have NodeList’s entries, forEach, keys, values method, but there is one more namedItem (filtering elements based on id and name) method...

Seeing the true appearance of these two guys, NodeList and HTMLCollection, we are very curious about these two guys. How was it possible to create something so similar but independent of each other? Under what circumstances does it get a NodeList, and under what circumstances does it get an HTMLCollection?

MDN introduces HTMLCollection like this:

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:
The reason why it is called HTMLCollection is because of some historical reasons. Before the emergence of the new generation of DOM, the collection that implemented the HTMLCollection interface only contained HTML elements, so it was named HTMLCollection.

我们知道DOM节点(node)不光包含HTML元素,还包含text node(字符节点)和comment(注释),既然HTMLCollection只包含HTML元素,那NodeList是不是会包含所有类型的DOM节点呢,我们来试验一下,先写一段html:

<p>
    this is patent content
    </p><p>
        this is child content
    </p>
    <!-- this is comment -->
Copy after login

然后执行:

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

打印结果:

Parsing of NodeList, HTMLCollection and Array

我们看到childNodes返回的是第一个p下面的所有DOM节点,包含3个text node(其中两个是换行符),一个子p,一个comment。这证实了我们对NodeList的猜想。

我们再看一下HTMLCollection,执行:

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

打印结果:

Parsing of NodeList, HTMLCollection and Array

只包含了子p,也验证了MDN上的说法。

至于parent即有childNodes属性,又有children属性呢?

因为parent即是一个Node对象(拥有childNodes属性),又因为它有子元素所以它又是一个ParentNode对象(拥有children属性)。

至此,我们对NodeList和HTMLCollection应该有一个比较全面的认识,总结一下就是HTMLCollection是比较早期的模型,只能包含HTML元素,早期就有的接口如document.getElementsByClassName, document.getElementsByTagName返回的就是HTMLCollection。NodeList是比较新的模型,相比HTMLCollection更加完善,不光有HTML元素,还有text节点和comment。比较新的接口如document.querySelectorAll返回的就是NodeList。

关于NodeList,HTMLCollection和Array的关系,就是长得像,有个别相似的功能,但是是完全不一样的东西。

当然关于HTMLCollection和NodeList的故事还没有讲完,因为它们有时候是live(活的?动态的?),有时候是not live(死的?静态的?),关于这个话题,之后的文章再详细分析。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

JavaScript创建对象的四种方式

浏览器与NodeJS的EventLoop异同以及部分机制

The above is the detailed content of Parsing of NodeList, HTMLCollection and Array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template