JS DOM: Get Parent, Child, Sibling
Get parent
node.parentElement-
Value is the parent of node, or
nullif none.
Get sibling
element.previousElementSibling-
Value is the previous sibling, or
nullif none. element.nextElementSibling-
Value is the next sibling or
nullif none.document.getElementsByTagName("p")[0].nextElementSibling.style.color = "green";
Get first/last child
element.firstElementChild-
Value is the first child, or
nullif none. element.lastElementChild-
Value is the last child, or
nullif 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.parentNodenode.previousSiblingnode.nextSiblingnode.firstChildnode.lastChildnode.childNodes-
node.hasChildNodes() -
Return
trueif it has children, including Whitespace Nodes. Elsefalse.document.getElementById("xd1d13").hasChildNodes();