FirstChild Can Be A Whitespace Text Node
innerHTML turns indentation into text nodes, so firstChild can hand back whitespace while firstElementChild and nextElementSibling stay on real elements.
Code
// HTML formatting becomes text nodes: firstChild may not be the element you meant
const host = document.createElement('div');
host.innerHTML = `
<span>alpha</span>
<span>beta</span>
`;
console.log(host.firstChild.constructor.name); // Text - the newline/indent node!
console.log(host.firstElementChild.textContent); // alpha - skips text nodes
// childNodes lists every node type; children lists elements only
console.log('childNodes:', host.childNodes.length); // 5 (text, span, text, span, text)
console.log('children:', host.children.length); // 2
// Sibling navigation has the same split: nextSibling vs nextElementSibling
const first = host.firstElementChild;
console.log(first.nextElementSibling.textContent); // beta
console.log(first.nextSibling.nodeType); // 3 (text node)What the demo exposes
innerHTML with indented markup inserts the newlines and spaces as text nodes. host.firstChild is therefore a Text node, and its constructor name prints Text, while firstElementChild skips past the whitespace and prints alpha from the real span.
Counting shows the same split: childNodes holds 5 nodes (text, span, text, span, text) but children holds 2. Sibling navigation mirrors it; nextElementSibling reaches beta while nextSibling lands on node type 3, another text node.
Points worth noting
- Whitespace-only text nodes count in childNodes and length.
- Element-only navigation is usually what DOM code intends.
Interactive Tools for This Topic
Diff Ignoring WhitespaceCompare two blocks of text line by line and separate true differences from lines that differ only in spacing, indentation, or line endings.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Whitespace NormalizerTrim line edges, collapse repeated spaces, convert tabs, and remove blank lines from text without changing its words or punctuation.
FAQ
- Why is firstChild not the first span?
- innerHTML preserved the template indentation as text nodes; the newline before the span is a Text node, so element access needs firstElementChild.
Report a problem with this exampleOpens a pre-filled issue on GitHub.