DOM Node Lists
DOM Node Lists represent collections of nodes that are returned by various DOM methods, such as querySelectorAll()
properties like childNodes
. A Node List is similar to an array in that it contains a list of nodes, but it is not an actual array and does not have all the methods available to arrays.
HTML DOM NodeList Object
- A NodeList object is a list (collection) of nodes extracted from an HTML 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 if the user uses the property childNodes.
- Most browsers return a NodeList object for the method querySelectorAll().
- The following code selects all <p> nodes in a document:
var myNodes = document.querySelectorAll("p");
The elements in the NodeList can be get by an index number.
To access the second <p> node user can use:
n = myNodes[1];
Input:-
Output :-
Note:- The index starts at 0
HTML DOM Node List Length
The length property defines the number of nodes in a node list:
Example 1:-
Input:-
Output :-
Example explained:
- Create a list of all <p> elements
- Display the length of the list
The length property is useful when you want to loop through the nodes in a node list:
Example 2:-
Input:-
Output (Before Click):-
Output (After Click):-
Difference Between an HTMLCollection and a NodeList
- An HTMLCollection is a collection of HTML elements while NodeList is a collection of document nodes.
- Both an HTMLCollection object and a NodeList object are an array-like lists (collections) of objects.
- Both have length properties defining the number of items in the list (collection).
- Both provide an index (0, 1, 2, 3, 4, ...) to access each item like an array.
- HTMLCollection items can be accessed by their name, id, or index number while NodeList items can only be accessed by their index number.
- Only the NodeList object can contain attribute nodes and text nodes.
Note:-
A node list may look like an array, but it is not.
You can loop through the node list and refer to the elements with a number (just like an array)
However, you cannot use array methods like valueOf(), pop(), push(), or join() on a node list.