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 / *Sibling properties include text and comment nodes, while *ElementChild / *ElementSibling skip 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

PropertyWhat it includes
childNodesAll child nodes — elements, text, comments
childrenOnly 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

PropertyIncludes text nodes?
nextSibling / previousSiblingYes
nextElementSibling / previousElementSiblingNo — 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

  1. parentNode walks up; childNodes / firstChild / nextSibling walk through all node types.
  2. Prefer *ElementChild and *ElementSibling for typical UI traversal.
  3. Pretty-printed HTML creates whitespace text nodes — a common source of “firstChild is not what I expected.”

Explain-It Challenge

Explain without notes:

  1. Why might ul.firstChild not be the first <li>?
  2. What is the difference between children and childNodes?
  3. Name the element-only alternative to nextSibling.

Navigation: ← 1.14.c — Fetching Elements · 1.14.e — Manipulating Elements →