Traverse Node Tree

Javascript DOM 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:

Document Object Model representation:

Javascript Document Object Model

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


Child Nodes

Javascript DOM 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.