← 中文资源

简体中文版本

replaceChildren 安全地重渲染列表

replaceChildren 一次换掉列表全部子节点:只接受节点所以比 innerHTML 安全,textContent 让不可信字符串保持纯文本;无参调用即清空。

阅读英文原文

实现说明

活动部件是函数 render。 本示例的循环部分是 for (const line of lines)。

使用要点

  • 这是浏览器侧代码——document 在 Node 里解析不到。
  • 演示输出是带标签的(first render :、rerender :、after clear :),每个操作都会留下自己的一行标注。

常见问题

「replaceChildren 安全地重渲染列表」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。

入口签名:function render(lines)

核心语句

const fragment = document.createDocumentFragment();
item.textContent = line; // 不可信字符串保持纯文本,不会被当作标记解析
fragment.append(item);
render(['deploy ok']); // 整体替换而不是追加:旧条目一并移除
console.log('rerender     :', log.children.length, 'item');

代码示例

// replaceChildren 一次替换全部子节点:只接受节点,不解析 HTML 字符串
const log = document.createElement('ul');
document.body.append(log);

function render(lines) {
  const fragment = document.createDocumentFragment();
  for (const line of lines) {
    const item = document.createElement('li');
    item.textContent = line; // 不可信字符串保持纯文本,不会被当作标记解析
    fragment.append(item);
  }
  log.replaceChildren(fragment);
}

render(['build ok', 'tests 42/42']);
console.log('first render :', log.children.length, 'items');

render(['deploy ok']); // 整体替换而不是追加:旧条目一并移除
console.log('rerender     :', log.children.length, 'item');

log.replaceChildren(); // 无参调用 = 清空
console.log('after clear  :', log.children.length, 'items');