replaceChildren Swaps List Content Safely

replaceChildren swaps a list's nodes in one call so rerenders are cheap, and textContent keeps untrusted strings inert instead of parsed markup.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
// 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');

Inside the snippet

replaceChildren Swaps List Content Safely keeps everything in the function render.

Repetition is confined to for (const line of lines) — the rest of the file is straight-line.

Points of care

  • document exist only in browsers — a Node runtime has no shims for them out of the box.

Putting it to use

Entry signature: function render(lines)

Running the file prints labeled results such as first render :, rerender :, after clear : — each operation’s effect is visible in the output.

Core lines

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

Interactive Tools for This Topic

FAQ

Does replaceChildren Swaps List Content Safely 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.