Traverse Node Tree
The W3C’s Document Object Model is an interface to the web pages provided by the browser venders. In order to work with the browser and web documents, JavaScript uses a hierarchical tree structure of parent and child Objects. Each element in the tree structure is called a Node. The root object in tree structure is the document object, which can have parents, children, and siblings and this determines by its position in the tree structure.
DOM Tree
Sample HTML Page:
<!DOCTYPE html>
<html>
<head>
<title>The DOM</title>
</head>
<body>
<h1>Document Object Model</h1>
<p id="pr">Test Paragraph</p>
</body>
</html>
Document Object Model representation:
When a web page is loaded in the browser, it creates a DOM of the web page. Each and every single element in the document will have a corresponding presence in the DOM.
To move among HTML elements, attributes, and text, you have to move among nodes in your tree structure. Nodes within the Document Object Model are represented by array-like node lists and the individual nodes themselves can be accessed via their Node Index. It doesn’t matter what is contained within the node, or rather, what sort of node it is. The following are the convenient properties for traversal:
Node.firstChild: Reference to the first child of the node
Node.lastChild: Reference to the last child of the node
Node.nextSibling: Reference to the next sibling of the node
Node.previousSibling: Reference to the previous sibling of the node
Example:
<!DOCTYPE html>
<html>
<body>
<p>Color List list:</p>
<ul id="colorlist"><li id="col1">Red</li><li id="col2">Blue</li><li id="col3">Green</li><li id="col3">Yellow</li><li id="col4">Violet</li></ul>
<button onclick="findColor()">Try it</button>
<script>
function findColor()
{
alert("First Child :" + document.getElementById("colorlist").firstChild.innerHTML);
alert("Last Child :" + document.getElementById("colorlist").lastChild.innerHTML);
alert("Next Sibling :" + document.getElementById("col3").nextSibling.innerHTML);
alert("Previous Sibling :" + document.getElementById("col3").previousSibling.innerHTML);
}
</script>
</body>
</html>
Child Nodes
There are several ways to find a node’s child nodes. The The child Nodes returns a collection of a node’s child nodes and the length property to determine the number of child nodes. You can loop through all child nodes for retrieving the information of child nodes.
<!DOCTYPE html>
<html>
<body>
<p>Child Nodes</p>
<button onclick="findColor()">Try it</button>
<script>
function findColor()
{
var childNodes = document.body.childNodes;
for(var i=0; i<=childNodes.length; i++) {
alert(childNodes[i].innerHTML)
}
}
</script>
</body>
</html>