A NodeList is an array-like collection (list) of Node Objects.
The nodes in a NodeList can be accessed by index (starts at 0).
The length property returns the number of nodes in a NodeList.
A NodeList is almost the same as an HTMLCollection.
See the description below.
The following properties and methods can be used on a NodeList:
Name | Description |
---|---|
entries() | Returns an Iterator with the key/value pairs from the list |
forEach() | Executes a callback function for each node in the list |
item() | Returns the node at a specified index |
keys() | Returns an Iterator with the keys from the list |
length | Returns the number of nodes in a NodeList |
values() | Returns an Iterator with the values from the list |
Select all <p>
nodes in a document:
const myNodeList = document.querySelectorAll("p");
The elements in the NodeList can be accessed by an index number.
To access the second <p> node you can write:
myNodeList[1]
Try it Yourself »
Note: The index starts at 0.
The length
property defines the number of nodes in a node list:
The length
property is useful when you want to loop through the nodes in a node list:
Change the color of all <p> elements in a node list:
const myNodelist = document.querySelectorAll("p");
for (let i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.color = "red";
}
Try it Yourself »
A NodeList is not an Array!
A NodeList may look like an array, but it is not.
You can loop through a NodeList and refer to its nodes with an index.
But you cannot use Array methods like push(), pop(), or join() on a NodeList.
A NodeList and an HTMLcollection is very much the same thing.
Both are array-like collections (lists) of nodes (elements) extracted from a document. The nodes can be accessed by index numbers. The index starts at 0.
Both have a length property that returns the number of elements in the list (collection).
An HTMLCollection is a collection of document elements.
A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes).
HTMLCollection items can be accessed by their name, id, or index number.
NodeList items can only be accessed by their index number.
An HTMLCollection is always a live collection. Example: If you add a <li> element to a list in the DOM, the list in the HTMLCollection will also change.
A NodeList is most often a static collection. Example: If you add a <li> element to a list in the DOM, the list in NodeList will not change.
The getElementsByClassName()
and getElementsByTagName()
methods return a live HTMLCollection.
The querySelectorAll()
method returns a static NodeList.
The childNodes
property returns a live NodeList.
In some cases, the NodeList is live: A change in the DOM updates the NodeList.
The childNodes
method returns a live NodeList.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!