← 中文资源

简体中文版本

Node.normalize 合并相邻文本节点

反复编辑 DOM 会留下相邻的文本节点:读者看到一段话,DOM 里却是三段;normalize 把它们合并并删掉空节点,选区与 Range 才能按单节点处理。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:heading、before、after。

使用要点

  • 浏览器才是这里的运行环境:document 在 Node 里拿不到。
  • 演示输出是带标签的(text nodes before:、merged text:、first child is a text node:),每个操作都会留下自己的一行标注。

常见问题

「Node.normalize 合并相邻文本节点」能在裸 Node.js 里跑吗?

不能——它用到 document。这些 API 只在浏览器里有效,裸 Node 进程没有这些能力,请放到页面(或 DevTools 控制台)里执行。

核心语句

heading.append('Deploy', document.createTextNode(' on Friday'), ' ');
const heading = document.querySelector('h1') as HTMLHeadingElement;
const before = heading.childNodes.length;

代码示例

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);