Javascript 简明教程

JavaScript - DOM Node Lists

DOM Node Lists

Node lists 类似于包含 HTML 元素的数组或 HTML collection 。但是,它与数组或 HTML 集合不同。

The Node lists are similar to an array or HTML collection containing the HTML elements. However, it is not the same as the array or HTML collection.

当您使用 querySelectorAll() 方法和 childNodes 属性时,所有现代浏览器都会返回节点列表。

All modern browsers return the node list when you use querySelectorAll() method and childNodes properties.

您可以将 NodeList 作为数组遍历,但不能在节点列表中使用其他数组方法,例如 map()、filter() 等。

You can traverse the NodeList as an array but can’t use other array methods like map(), filter(), etc. with node lists.

Example

Using the forEach() method to traverse the node list elements

在下面的程序中,我们定义了四个 <p> 元素,包含各种语言。

In the below program, we have defined four <p> elements containing the various languages.

在那之后,我们使用 querySelectorAll() 方法在节点列表中获取元素,其中有等于“lang”的类名。在那之后,我们使用 forEach() 方法遍历节点列表并打印各元素的 HTML。

After that, we use the querySelectorAll() method to get all elements having a class name equal to 'lang' in the node list. After that, we traverse the node list using the forEach() method and print the HTML of each element.

<DOCTYPE html>
<html>
<body>
   <p class = "lang"> English </p>
   <p class = "lang"> German </p>
   <p class = "lang"> Arabic </p>
   <p class = "lang"> Hindi </p> <br>
   <div id = "output"> </div>
   <script>
      const output = document.getElementById('output');
      output.innerHTML += "All languages are: <br>";
      const langs = document.querySelectorAll('.lang');
      langs.forEach((language) => {
         output.innerHTML += language.innerHTML + '<br>';
      })
   </script>
</body>
</html>

Example: Getting the length of the node list

在下面的代码中,我们使用节点列表的“length”属性来计算节点列表中的节点数。

In the below code, we have used the 'length' property of the node list to count the number of nodes in the node list.

<DOCTYPE html>
<html>
<body>
   <div class = "fruit"> Apple </div>
   <div class = "fruit"> Orange </div>
   <div class = "fruit"> Banana </div>
   <div class = "fruit"> Mango </div>
   <div id = "output">Total number of fruits are : </div>
   <script>
      const fruits = document.querySelectorAll('.fruit');
      document.getElementById('output').innerHTML += fruits.length;
   </script>
</body>
</html>

Difference between HTMLCollection and NodeList

HTML 集合和节点列表看起来很相似,但它们之间有一个细微的差别,这一点我们在下表中已经进行了说明。

The HTML collection and Node list look similar, but there is a minor difference between them, which we have explained in the table below.

Feature

HTMLCollection

NodeList

Return by

Generally, getElementByClassName(), getElementByTagName methods, and children properties return the HTML collection.

Generally, the querySelectorAll() method and childNodes property return the Node list.

Array methods

It supports limited array methods.

It also supports limited array methods like forEach().

Live collection

Some browser supports live collection with HTML collection.

It updates if you update the DOM element.