Easy Tutorial
❮ Dom Prop Document Documenturi Met Element Clonenode ❯

XML DOM - Traversing the Node Tree

Traversing means looping or moving through the node tree.

Traversing the Node Tree

You often want to loop through an XML document, for example: when you need to extract the value of each element.

This is called "traversing the node tree".

The following example traverses all child nodes of <book> and displays their names and values:

Example

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var x, i, xmlDoc;
var txt = "";
var text = "<book>" + 
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book>";

parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");

// documentElement represents the root node
x = xmlDoc.documentElement.childNodes;
for (i = 0; i < x.length ;i++) {
    txt += x[i].nodeName + ": " + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

Output:

title: Everyday Italian
author: Giada De Laurentiis
year: 2005

Example Explanation:

❮ Dom Prop Document Documenturi Met Element Clonenode ❯