JS DOM: Get Element Parent, Child, Sibling
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
node.parentElement-
Value is the parent of node, or
nullif none.
Get Previous/Next Sibling
element.previousElementSibling-
Value is the previous sibling, or
nullif none. (ignore Whitespace Nodes) element.nextElementSibling-
Value is the next sibling or
nullif none. (ignore Whitespace Nodes)document.getElementsByTagName("p")[0] .nextElementSibling.style.color = "green";
Get First/Last Child
element.firstElementChild-
Value is the first child, or
nullif none. (ignore Whitespace Nodes) element.lastElementChild-
Value is the last child, or
nullif none. (ignore Whitespace Nodes)
Get Child Nodes
element.children-
Value is the element's children.
result is a Live Object and HTMLCollection. 〔see JS DOM: NodeList vs HTMLCollection〕 (ignore Whitespace Nodes)
const xx = document.body; for (let x of xx.children) x.style.color = "green";
Not Ignore Whitespace Nodes
The following may return Whitespace Nodes .
node.parentNode- ◆
node.previousSibling- ◆
node.nextSibling- ◆
node.firstChild- ◆
node.lastChild- ◆
node.childNodes- ◆
-
node.hasChildNodes() -
Return
trueif it has children, including Whitespace Nodes. Elsefalse.document.getElementById("xd1d13").hasChildNodes()
Basic DOM Element Methods
- JS DOM: Node, Node Type, Element
- JS DOM: Get Element by ID, Name, Class etc
- JS DOM: Get Element Parent, Child, Sibling
- JS DOM: NodeList vs HTMLCollection
- JS DOM: Iterate HTMLCollection
- JS DOM: Element Attribute Methods
- JS DOM: List, Add, Remove Class Attribute
- JS DOM: Create Element, Clone
- JS DOM: Insert, Remove, Replace Element
- JS DOM: Change Element Content
- JS DOM: Add, Remove Event Handler