JS DOM: Get Parent, Child, Sibling

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.parentElement

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

Get Sibling

element.previousElementSibling

Value is the previous sibling, or null if none. (ignores Whitespace Nodes)

element.nextElementSibling

Value is the next sibling or null if none. (ignores 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. (ignores Whitespace Nodes)

element.lastElementChild

Value is the last child, or null if none. (ignores Whitespace Nodes)

Get All Children

element.children

Value is the element's children.

result is a Live Object and HTMLCollection. [see JS DOM: NodeList vs HTMLCollection] (ignores Whitespace Nodes)

const xx = document.body;
for (let x of xx.children) x.style.color = "green";

Include 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();

DOM Element Methods

Get node
Loop thru nodes
Attributes
Create insert node
Delete
Change content
Event