Episode 7 of 18
Traversing the DOM (part 1)
Navigate the DOM tree — move from parent to child and access siblings using parentNode, children, firstChild, and lastChild.
Traversing the DOM (part 1)
Instead of selecting elements by ID or class every time, you can traverse the DOM tree — move from one node to its parent, children, or siblings. This is useful when you already have a reference to one element and need to reach related elements.
Parent Node
var item = document.querySelector('li');
console.log(item.parentNode); // The <ul> element
console.log(item.parentElement); // The <ul> element (same, but element-only)
// Go up multiple levels
console.log(item.parentNode.parentNode); // The container above <ul>
Children
var list = document.querySelector('ul');
console.log(list.children); // HTMLCollection of <li> elements
console.log(list.children[0]); // First <li>
console.log(list.children.length); // Number of child elements
console.log(list.firstElementChild); // First child element
console.log(list.lastElementChild); // Last child element
Node vs Element Traversal
| All Nodes | Elements Only |
|---|---|
parentNode | parentElement |
childNodes | children |
firstChild | firstElementChild |
lastChild | lastElementChild |
The "all nodes" properties include text and comment nodes. The "elements only" properties skip them — which is usually what you want.
Practical Example
<div class="container">
<ul id="ninja-list">
<li>Ryu</li>
<li>Ken</li>
<li>Yoshi</li>
</ul>
</div>
var list = document.querySelector('#ninja-list');
console.log(list.children[0].textContent); // "Ryu"
console.log(list.firstElementChild.textContent); // "Ryu"
console.log(list.lastElementChild.textContent); // "Yoshi"
console.log(list.parentElement.className); // "container"
Key Takeaways
parentNode/parentElementmoves up the treechildrenreturns only element children (no text nodes)firstElementChildandlastElementChildgive you the first/last child element- Prefer the "Element" versions to avoid dealing with text and comment nodes