The NodeList Object/Interface
The NodeList object/interface is an ordered collection of nodes. Ordered means that they have a numbered place in a sequence.
The childNodes property of the Node object returns a NodeList, as shown in Listing 16.4.
Listing 16.4 A Property of an Object Returning a NodeList Object
1: //var docroot holds the root element of the document 2: var children = docRoot.childNodes;
Table 16.5 gives an overview of the NodeList object properties.
| Table 16.5 NodeList Attributes/Properties | |
|
|
|
| Name | Value |
|---|---|
|
|
|
| length | The number of nodes in the NodeList |
|
|
|
Listing 16.6 shows a JavaScript example using this property.
Listing 16.6 Getting the Length of a NodeList
1: //children holds the NodeList Object with the child nodes 2: var nrofchildren = children.length;
Table 16.6 gives an overview of the NodeList object methods.
| Table 16.6 NodeList Methods | |
|
|
|
| Name | Returns |
|---|---|
|
|
|
| item(n) | The nth item (node) of the collection |
|
|
|
Listing 16.7 shows a JavaScript example using this method.
Listing 16.7 Using the nth Item of a NodeList
1: //children holds the NodeList Object with the child nodes 2: var i; 3: for (i=0, i < children.length, i++) //loop over all child nodes 4: return children.item(i).nodeName; //return the names
| We use a variable, I, for iterating over all the items of a NodeList containing the list of children. |
In line 4 we return the name for every child (the tag name if the child is an element, the attributename if an attribute, and so on.