Table of Contents
NodeList
Print result
entries():
forEach():
item():
keys():
values():
HTMLCollection
Home Web Front-end JS Tutorial Parsing of NodeList, HTMLCollection and Array

Parsing of NodeList, HTMLCollection and Array

Jul 07, 2018 pm 05:30 PM
html html5 javascript

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

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles