Click to return to the XML (Extensible Markup Language) home page    
Using the XMLDOMNode Obje...     Using the XMLDOMNamedNode...     XML DOM User Guide    
Web Workshop  |  XML (Extensible Markup Language)

Using the XMLDOMNodeList Object


The XMLDOMNodeList object is returned by the childNodes property and the selectNodes and getElementsByTagName methods.

Gathering Information About the Node List

You can get the length of the node list from the length property. The length can be used for, among other things, iterating through the list of children. For example, the following sample code loops through the children of "elem1" searching for a child element with the text value of "hello world." If such a child exists, the index of that child is assigned to the variable "helloWorldIndex."

for (i = 0;i < elem1.childNodes.length;i++){
  if (elem1.childNodes.item(i).text == "hello world")
    helloWorldIndex = i;
  }

Navigating the Node List

You can get at a specific member of the node list with the item method. The item method takes a number corresponding to a node's position within the node list. To get the first node in the node list, for instance, one would call the following method: item(0). It is also possible to navigate through the node list using the nextNode method. The nextNode method returns the next node in the node list.

The following code sample performs the same task as the previous code sample.

currentNode = elem1.childNodes.nextNode;
while (currentNode != null) {
  if (currentNode.text == "hello world")
    helloWorldNode = currentNode;
  currentNode = elem1.childNodes.nextNode;
  }

Notice that the currentNode is set using the node returned by elem1.childNodes.nextNode. The initial position of the node list is defined to be before the first node. Therefore, the first time nextNode is called on the node list, the first node is returned. Also notice that the code tests for currentNode != null. If the current node is the last node in the list or the node list has no members, nextNode returns null.



Back to topBack to top

Did you find this topic useful? Suggestions for other topics? Write us!

© 1999 Microsoft Corporation. All rights reserved. Terms of use.