JavaScript: Get Element's Parent/Child/Sibling, Navigate DOM Tree

By Xah Lee. Date: . Last updated: .

Here is how to navigate the DOM tree. That is, if you have a HTML Element or XML Node, you can get its parent node, sibling node, or children nodes.

Get Parent Node

node.parentElement
Value is the parent of node, or null if none.

Get Previous/Next Sibling

element.previousElementSibling
Value is the previous sibling, or null if none.
(ignore Whitespace Nodes)
element.nextElementSibling
Value is the next sibling or null if none.
(ignore Whitespace Nodes)
document.getElementsByTagName("p")[0] .nextElementSibling.style.color = "green";

Get First/Last Child

element.firstElementChild
Value is the first child, or null if none.
(ignore Whitespace Nodes)
element.lastElementChild
Value is the last child, or null if none.
(ignore Whitespace Nodes)

Get Child Nodes

element.children
Value is the element's children. (Live Object and HTMLCollection)
(ignore Whitespace Nodes)
const xx = document.body;
for (let x of xx.children) x.style.color = "green";

Not Ignore Whitespace Nodes

The following may return Whitespace Nodes .

node.parentNode
node.previousSibling
node.nextSibling
node.firstChild
node.lastChild
node.childNodes
node.hasChildNodes()
Return true if it has children, including Whitespace Nodes. Else false.

document.getElementById("xd1d13").hasChildNodes()
BUY ΣJS JavaScript in Depth

Basic DOM Element Methods