Search within TutorialsPark

Javascript DOM: Navigating the Tree


Use Javascript DOM methods to Navigate the DOM Tree


Javascript DOM : Navigating the DOM Tree

A good way to search for elements within the document is to treat the DOM as a tree and then navigate along its hierarchical structure.

Javascript DOM provides a set a of properties and methods that enables the user to do just that.

Table : Location Object Properties and Methods

Property Description Returns
childNodes To Return the set of child Elements HTMLElement[]
firstChild To return the first child Element HTMLElement
hasChildNodes() A value true is returned if the current element has child elements boolean
lastChild Returns the last child element of the specified node HTMLElement
nextSibling It Returns the sibling element defined after the current element HTMLElement
parentNode To Return the parent element HTMLElement
previousSibling To Return the sibling element defined before the current element HTMLElement

Javascript DOM Property: childNodes

The Javascript DOM childNodes property returns an array like list(called a NodeList) of the immediate child nodes of the specified element

In the below demo, the element selected is <ul> , which is then used to find all the immediate childnodes within <ul>

Example: Javascript DOM : Tree navigation using childnodes Objects

Give it a TRY! » Note: A childnode is a read-only array like object, representing the Node's child nodes.


Javascript DOM property : firstChild and lastChild

The Javascript DOM property firstChild is used to select the first child element of a given Node.

And property lastChild is used to select the last child element of a given Node.

Example: Javascript DOM - firstChild and lastChild property

Give it a TRY! » Note: Incase a node has no child element, a null is returned.


Javascript DOM property : nextSibling and previousSibling

The Javascript DOM Node property nextSibling returns the next child node of an element at the same level as the current child node.

Similarly, the DOM Node property previousSibling returns the previous child node of an element at the same level as the current child node.

Example: Javascript DOM property previousSibling and Method

Give it a TRY! » Note: If no match is found then a null value is returned.


Javascript DOM Node Property: parentNode

The Javascript DOM Node property parentNode returns the element that contains the current node.

Example: Javascript DOM : Search using CSS Selectors

Give it a TRY! » Note: The selector querySelectorAll() can select multiple elements.


Javascript DOM Node Method : hasChildNodes()

The Javascript DOM Node Method hasChildNodes() checks the specified element and returns true if the current element has one or more child elements or false if none.

Example: Javascript DOM Node Method - hasChildNodes()

Give it a TRY! » Note: The returns value is a booleantrue or false