現代前端開發頻繁需要動態插入標籤:無限滾動載入、即時搜尋結果、表單動態增欄、模態框內容注入。選擇正確 API 能兼顧效能、安全與維護性。
| 方法 | 插入位置 | 回傳值 | 效能 | 安全性 | 適用場景 |
|---|---|---|---|---|---|
insertAdjacentHTML(position, html) | beforebegin, afterbegin, beforeend, afterend | undefined | ⚡ 快(單次解析) | ⚠️ 需自行淨化 | 大量 HTML 片段插入、指定精確位置 |
element.innerHTML = html | 替換全體子內容 | undefined | ⚡ 快 | ⚠️ 需自行淨化 | 整區塊重渲染 |
element.append(...nodes) | 子節點末尾 | undefined | 🔄 中(建立節點) | ✅ 安全(文字節點不解析) | 動態建立元素、避免 XSS |
element.prepend(...nodes) | 子節點開頭 | undefined | 🔄 中 | ✅ 安全 | 新增至列表開頭 |
element.before(...nodes) | 元素之前(同層) | undefined | 🔄 中 | ✅ 安全 | 插入同級元素 |
element.after(...nodes) | 元素之後(同層) | undefined | 🔄 中 | ✅ 安全 | 插入同級元素 |
element.replaceWith(...nodes) | 替換元素本身 | undefined | 🔄 中 | ✅ 安全 | 元素替換 |
<div id="container">
<!-- beforebegin -->
<div>
<!-- afterbegin -->
<p>現有內容</p>
<!-- beforeend -->
</div>
<!-- afterend -->
</div>
// ❌ 危險:直接插入使用者輸入
container.insertAdjacentHTML('beforeend', userInput);
// ✅ 安全:DOMPurify 淨化後插入
import DOMPurify from 'dompurify';
const cleanHTML = DOMPurify.sanitize(userInput, {
ALLOWED_TAGS: ['p', 'br', 'b', 'i', 'strong', 'em', 'a'],
ALLOWED_ATTR: ['href', 'target', 'rel']
});
container.insertAdjacentHTML('beforeend', cleanHTML);
// ✅ 更安全:使用 DOM API 建立節點(完全避免 HTML 解析)
function createSafeElement(tag, attributes = {}, ...children) {
const el = document.createElement(tag);
Object.entries(attributes).forEach(([key, value]) => {
if (key.startsWith('on')) return; // 拒絕事件屬性
el.setAttribute(key, value);
});
children.forEach(child => {
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
} else if (child instanceof Node) {
el.appendChild(child);
}
});
return el;
}
// 使用
const link = createSafeElement('a', { href: url, target: '_blank', rel: 'noopener' }, '連結文字');
container.append(link);
function appendManyItems(container, items) {
const fragment = document.createDocumentFragment();
items.forEach(item => {
const div = document.createElement('div');
div.className = 'item';
div.textContent = item.text; // 純文字,安全
fragment.appendChild(div);
});
// 單次重排/重繪
container.appendChild(fragment);
}
// 虛擬滾動配合:只渲染可視區
// 推薦使用 @tanstack/virtual, react-window, vue-virtual-scroller
<template id="item-template">
<article class="card">
<h3 class="title"></h3>
<p class="desc"></p>
<a class="link" href="#">閱讀更多</a>
</article>
</template>
function renderItem(data) {
const template = document.getElementById('item-template');
const clone = template.content.cloneNode(true); // DocumentFragment
clone.querySelector('.title').textContent = data.title;
clone.querySelector('.desc').textContent = data.description;
clone.querySelector('.link').href = data.url;
return clone;
}
// 批次渲染
const fragment = document.createDocumentFragment();
dataList.forEach(item => fragment.appendChild(renderItem(item)));
container.appendChild(fragment);
<template> + cloneNode + textContent 模式$(html).appendTo(container) 內部用 innerHTML,**務必先 DOMPurify**// 監聽所有 DOM 插入(開發模式)
const observer = new MutationObserver(mutations => {
mutations.forEach(m => {
if (m.type === 'childList' && m.addedNodes.length) {
console.log('新增節點:', m.addedNodes);
}
});
});
observer.observe(document.body, { childList: true, subtree: true });
動態插入 HTML 以 DOM API(append/prepend/textContent)為首選(天然安全),大量 HTML 片段用 insertAdjacentHTML + DOMPurify,超大列表採用 DocumentFragment + 虛擬滾動, 元素則是無框架專案的最佳模板方案。