Open Playground
JS HTML DOMLesson #269

JavaScript HTML DOM Node Lists

A NodeList object is a list (collection) of nodes extracted from a document.

The HTML DOM NodeList Object

A NodeList object is a list (collection) of nodes extracted from a document.

A NodeList object is almost the same as an HTMLCollection object.

Some (older) browsers return a NodeList object instead of an HTMLCollection for methods like getElementsByClassName().

All browsers return a NodeList object for the property childNodes.

Most browsers return a NodeList object for the method querySelectorAll().

The following code selects all nodes in a document:

Example

Example Code

javascript
Try it Yourself
const myNodeList = document.querySelectorAll("p");

Note: The index starts at 0.


HTML DOM Node List Length

The length property defines the number of nodes in a node list:

Example

Example Code

javascript
Try it Yourself
myNodelist.length

The length property is useful when you want to loop through the nodes in a node list:

Example

```javascript const myNodelist = document.querySelectorAll("p");

for (let i = 0; i 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 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.


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 by index. > But, you cannot use Array methods like push(), pop(), or join() on a NodeList.


Interactive Code Examples

JS Example 1

javascript
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview:

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
myNodelist.length

JS Example 3

javascript
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview: