JS DOM: Get Parent, Child, Sibling

By Xah Lee. Date: . Last updated: .

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.

element.nextElementSibling

Value is the next sibling or null if none.

document.getElementsByTagName("p")[0].nextElementSibling.style.color = "green";

Get First/Last Child

element.firstElementChild

Value is the first child, or null if none.

element.lastElementChild

Value is the last child, or null if none.

Get All Children

element.children

Value is the element's children.

result is a Live Object and HTMLCollection.

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