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.
Code
// 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
documentexist 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
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.