JS: 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
null
if none.
Get Previous/Next Sibling
element.previousElementSibling
-
Value is the previous sibling, or
null
if none. (ignore Whitespace Nodes) element.nextElementSibling
-
Value is the next sibling or
null
if none. (ignore Whitespace Nodes)document.getElementsByTagName("p")[0] .nextElementSibling.style.color = "green";
Get First/Last Child
element.firstElementChild
-
Value is the first child, or
null
if none. (ignore Whitespace Nodes) element.lastElementChild
-
Value is the last child, or
null
if none. (ignore Whitespace Nodes)
Get Child Nodes
element.children
-
Value is the element's children.
result is a Live Object and HTMLCollection. 〔see 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
true
if it has children, including Whitespace Nodes. Elsefalse
.document.getElementById("xd1d13").hasChildNodes()
Basic DOM Element Methods
- JS: What is Node, Node Type, Element
- JS: Get Element by ID, Name, Class etc
- JS: Get Element Parent, Child, Sibling
- DOM: NodeList vs HTMLCollection
- JS: Iterate HTMLCollection
- JS: Element Attribute Methods
- JS: List, Add, Remove Class Attribute
- JS: Create Element, Clone
- JS: Insert, Remove, Replace Element
- JS: Change Element Content
- JS: Add, Remove Event Handler