DOM: Navigate DOM Tree
Here is 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 ]
node.parentNode
node.previousSibling
node.nextSibling
node.firstChild
node.lastChild
node.childNodes