appendChild() 是 DOM 操作最基礎也最關鍵的方法:將節點添加到指定父節點的子節點列表末尾。理解其「移動而非複製」特性與 DocumentFragment 批量優化,是前端性能優化的入門必修課。
parent.appendChild(childNode);
// 特性:
// 1. childNode 若已在文檔中 → 移動 (非複製),保留事件/數據
// 2. 返回值:插入的 childNode (便於鏈式操作)
// 3. 只接受單個節點,不支持多參數、字符串、數組
// 4. 文本需用 createTextNode 或 textContent 設置
<html>
<head>
<script>
function appendDemo() {
// 1. 創建元素節點
const p = document.createElement('p');
// 2. 創建文本節點
const text = document.createTextNode('你好,世界');
// 3. 獲取父容器
const container = document.getElementById('container');
// 4. 組裝並追加
container.appendChild(p); // 先掛載 p
p.appendChild(text); // 再給 p 加文本
}
</script>
<style>
p { width: 100px; height: 100px; background: green; }
#container p { background: blue; } /* 更高優先級 */
</style>
</head>
<body>
<div id="container"><p>hello world</p></div>
<p>說兩句吧</p>
<hr>
<button onclick="appendDemo()">追加節點</button>
</body>
</html>
const li = document.createElement('li');
li.textContent = '項目';
ul1.appendChild(li); // 在 ul1 中
ul2.appendChild(li); // 移動到 ul2,ul1 中不再有
若需複製,用 cloneNode(true)。
// ❌ 極差:每次 append 觸發重排重繪
for (let i = 0; i < 10000; i++) {
const li = document.createElement('li');
li.textContent = `項目 ${i}`;
ul.appendChild(li); // 10000 次重排!
}
// ✅ 最佳:離線構建,一次掛載
const frag = document.createDocumentFragment();
for (let i = 0; i < 10000; i++) {
const li = document.createElement('li');
li.textContent = `項目 ${i}`;
frag.appendChild(li); // 離線操作,無重排
}
ul.appendChild(frag); // 僅 1 次重排重繪
// 原生現代 API (IE 不支持)
parent.append(node1, node2, "文本", document.createTextNode("更多"));
parent.prepend(node1, "開頭文本");
// 兼容性封裝
function appendAll(parent, ...nodes) {
const frag = document.createDocumentFragment();
nodes.forEach(n => {
if (typeof n === 'string') n = document.createTextNode(n);
else if (n instanceof DocumentFragment) { /* 已是片段 */ }
frag.appendChild(n);
});
parent.appendChild(frag);
}
function renderList(data, templateId, container) {
const template = document.getElementById(templateId);
const frag = document.createDocumentFragment();
data.forEach(item => {
const clone = template.content.cloneNode(true); // 標籤
// 綁定數據...
clone.querySelector('.name').textContent = item.name;
frag.appendChild(clone);
});
container.appendChild(frag);
}
| 方法 | 位置 | 參考節點 | 常見用途 |
|---|---|---|---|
| appendChild | 末尾 | 無 | 列表追加、構建樹 |
| insertBefore | 參考節點前 | 必需 | 有序插入、插入排序 |
| replaceChild | 替換參考節點 | 必需 | 節點替換、虛擬 DOM 更新 |
掌握 appendChild + DocumentFragment 的組合拳,是原生 DOM 高性能渲染的基石。