Episode 1 — Fundamentals / 1.14 — DOM Manipulation
1.14.d — DOM Tree Traversal
In one sentence: Every node knows its parent, children, and siblings — but
*Child/*Siblingproperties include text and comment nodes, while*ElementChild/*ElementSiblingskip straight to elements (usually what you want in UI code).
Navigation: ← 1.14.c — Fetching Elements · 1.14.e — Manipulating Elements →
1. Parent link: parentNode
const span = document.querySelector("span");
span.parentNode; // often an Element; for detached nodes may be a DocumentFragment
parentElement — same idea but only returns an Element parent (or null if parent is not an element, e.g. a document node edge cases — in practice both are common for normal elements).
2. Children: childNodes vs children
| Property | What it includes |
|---|---|
childNodes | All child nodes — elements, text, comments |
children | Only element children (HTMLCollection, live) |
<ul>
<li>One</li>
</ul>
If the <ul> contains newline + spaces between tags, childNodes may include text nodes before the first <li>.
3. firstChild / lastChild
firstChild — first node (often whitespace text).
firstElementChild — first element child (preferred for UI).
list.firstElementChild?.textContent;
Same pattern: lastChild vs lastElementChild.
4. Siblings: nextSibling / previousSibling
| Property | Includes text nodes? |
|---|---|
nextSibling / previousSibling | Yes |
nextElementSibling / previousElementSibling | No — elements only |
heading.nextElementSibling; // often the <p> after an <h2>
5. Why interviews still emphasize childNodes / firstChild
Historical APIs and jQuery-era code use node lists including whitespace. Modern components often avoid manual sibling walking — but debugging still exposes text nodes in DevTools.
6. Walking a subtree (pattern)
function walk(element) {
for (const child of element.children) {
walk(child);
}
}
Use children + recursion for element-only trees; use childNodes only when you intentionally process text nodes.
7. Key takeaways
parentNodewalks up;childNodes/firstChild/nextSiblingwalk through all node types.- Prefer
*ElementChildand*ElementSiblingfor typical UI traversal. - Pretty-printed HTML creates whitespace text nodes — a common source of “
firstChildis not what I expected.”
Explain-It Challenge
Explain without notes:
- Why might
ul.firstChildnot be the first<li>? - What is the difference between
childrenandchildNodes? - Name the element-only alternative to
nextSibling.
Navigation: ← 1.14.c — Fetching Elements · 1.14.e — Manipulating Elements →