DOM: Navigate DOM Tree

By Xah Lee. Date: . Last updated: .

Here's how to navigate the DOM tree. That is, if you have a 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.

Get Previous/Next Sibling

element.previousElementSibling
Value is the previous sibling that's not a whitespace node. null if none.
element.nextElementSibling
Value is the next sibling that's not a whitespace node. null if none.
document.getElementsByTagName("p")[0] .nextElementSibling.style.color = "green";

Get First/Last Child

element.firstElementChild
Value is the first non-whitespace child node of element, or null if none.
element.lastElementChild
Value is the last non-whitespace child node of element, or null if none.

Get Child Nodes

element.children
Value is a live collection of all non-whitespace children of element. [see DOM: Whitespace Nodes]
const x = document.body .children;
Array.from ( x ) .forEach ((x => { x.style.color="green" }));

Not Ignore Whitespace Nodes

The following may return Whitespace Nodes.

[see DOM: Whitespace Nodes ]

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


DOM

Overview

Basic Examples

HTML Input

Web Scripting Examples

Web Scripting Misc

jQuery

node.js