Node.normalize Merges Adjacent Text Nodes
Repeated DOM edits leave adjacent text nodes where the reader sees one string; normalize() merges them and drops empty ones so ranges see a single node.
Code
const heading = document.querySelector('h1') as HTMLHeadingElement;
// Repeated edits leave adjacent text nodes behind: three nodes where the
// reader sees one continuous string.
heading.textContent = '';
heading.append('Deploy', document.createTextNode(' on Friday'), ' ');
// normalize() merges adjacent text nodes and drops empty ones, so ranges,
// selections and text metrics see a single node instead of three.
const before = heading.childNodes.length;
heading.normalize();
const after = heading.childNodes.length;
console.log('text nodes before:', before, 'after:', after);
console.log('merged text:', JSON.stringify(heading.textContent));
console.log('first child is a text node:', heading.firstChild?.nodeType === Node.TEXT_NODE);What to notice first — Node.normalize Merges Adjacent Text Nodes
Both state and work sit in top-level bindings: heading, before, after.
What to watch for
- Come with the language toolchain installed and nothing else is missing.
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Putting it to use
Output lines are prefixed (text nodes before:, merged text:, first child is a text node:), so the log itself documents which step fired.
Core lines
heading.append('Deploy', document.createTextNode(' on Friday'), ' ');
const heading = document.querySelector('h1') as HTMLHeadingElement;
const before = heading.childNodes.length;
Interactive Tools for This Topic
FAQ
- Does Node.normalize Merges Adjacent Text Nodes run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.