萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript appendChild() 追加節點完整教學與性能優化

原生 appendChild() 節點追加核心指南:從基礎到高性能批量操作

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)。

性能殺手:循環中逐個 appendChild


// ❌ 極差:每次 append 觸發重排重繪
for (let i = 0; i < 10000; i++) {
  const li = document.createElement('li');
  li.textContent = `項目 ${i}`;
  ul.appendChild(li); // 10000 次重排!
}

黃金優化:DocumentFragment


// ✅ 最佳:離線構建,一次掛載
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 次重排重繪

現代替代:append() / prepend() (支援多參數、字符串)


// 原生現代 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);
}

實戰模式:模板克隆 + Fragment 批量渲染

function renderList(data, templateId, container) {
  const template = document.getElementById(templateId);
  const frag = document.createDocumentFragment();
  
  data.forEach(item => {
    const clone = template.content.cloneNode(true); //