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.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// 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

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.