home HOME

XML DOM Tutorial
DOM HOME
DOM Introduction
DOM Nodes
DOM Node Tree
DOM Node Access
DOM Node Info
DOM Node List
DOM Parsing
DOM Traverse Nodes
DOM Mozilla vs IE
DOM Navigate Nodes

Manipulate Nodes
DOM Get Nodes
DOM Set Nodes
DOM Remove Nodes
DOM Replace Nodes
DOM Create Nodes
DOM Add Nodes
DOM Clone Nodes

XML DOM Reference
DOM Node Types
DOM Node
DOM NodeList
DOM NamedNodeMap
DOM Document
DOM DocumentImpl
DOM DocumentType
DOM ProcessingInstr
DOM Element
DOM Attribute
DOM Text
DOM CDATA
DOM Comment
DOM HttpRequest
DOM ParseError

DOM Summary

Examples
DOM Examples
DOM Validator

Selected Reading
Web Statistics
Web Glossary
Web Hosting
Web Quality

W3Schools Forum

Helping W3Schools

pixels

XML DOM Traverse Node Tree

prev next

Examples

Traverse node tree
This example shows how to loop through all child nodes of <note>, and print the node name and the node value.


Traversing the Node-tree

Often you will need to loop through elements in an XML document or string.

The example below loops through all child nodes of <note>, and prints the node name and the node value of each node:

<html>
<body>
<script type="text/javascript">
var text="<note>";
text=text+"<to>Tove</to>";
text=text+"<from>Jani</from>";
text=text+"<heading>Reminder</heading>";
text=text+"<body>Don't forget me this weekend!</body>";
text=text+"</note>";
// code for IE
if (window.ActiveXObject)
  {
  var doc=new ActiveXObject("Microsoft.XMLDOM");
  doc.async="false";
  doc.loadXML(text);
  }
// code for Mozilla, Firefox, Opera, etc.
else
  {
  var parser=new DOMParser();
  var doc=parser.parseFromString(text,"text/xml");
  }
// documentElement always represents the root node
var x=doc.documentElement;
for (i=0;i<x.childNodes.length;i++)
  {
  document.write(x.childNodes[i].nodeName);
  document.write("=");
  document.write(x.childNodes[i].childNodes[0].nodeValue);
  document.write("<br />");
  }
</script>
</body>
</html>

Output:

to=Tove
from=Jani
heading=Reminder
body=Don't forget me this weekend!


prev next

Jump to: Top of Page or HOME or Printer Friendly Printer friendly page

W3Schools provides material for training only. We do not warrant the correctness of its contents. The risk from using it lies entirely with the user. While using this site, you agree to have read and accepted our terms of use and privacy policy.

Copyright 1999-2007 by Refsnes Data. All Rights Reserved.

Validate Validate W3C-WAI level A conformance icon W3Schools was converted to XHTML in December 1999