萬盛學電腦網

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

DOM replaceChild() 方法替換節點完整教學與實戰陷阱

DOM replaceChild() 節點替換核心原理與實戰指南

replaceChild(newNode, oldNode) 是 父節點 的方法,用新節點替換舊子節點。理解「父節點視角」是正確使用的關鍵。

核心三步驟

  1. 創建新節點(createElement、createTextNode、cloneNode)
  2. 定位舊節點(遍歷、querySelector、children[index])
  3. 調用 parentNode.replaceChild(newNode, oldNode)

完整演示代碼

<html>
<head>
  <script>
    function replaceNode() {
      // 1. 創建新節點
      const newLi = document.createElement('li');
      const newText = document.createTextNode('白天');
      newLi.appendChild(newText);
      
      // 2. 定位父節點與舊節點
      const parentUl = document.getElementsByTagName('ul')[0];
      const oldLi = parentUl.children[2]; // 第3個 li (索引2)
      
      // 3. 父節點視角替換
      parentUl.replaceChild(newLi, oldLi);
    }
  </script>
</head>
<body>
  <div id="container">
    <ul>
      <li>春天</li>
      <li>夏天</li>
      <li>藍天</li>  <!-- 將被替換 -->
      <li>秋天</li>
      <li>冬天</li>
    </ul>
  </div>
  <button onclick="replaceNode()">替換節點</button>
</body>
</html>

關鍵特性與注意事項

特性說明
返回值返回被替換的舊節點(可保存引用以便撤銷)
舊節點從 DOM 移除但未銷毀,保留事件/數據,可再次插入
新節點若已在文檔中,會先被移除再插入(移動而非複製)
事件保留舊節點綁定的事件隨節點保留,新節點無事件
文本節點可直接替換文本節點:`parent.replaceChild(newText, oldText)`

常見錯誤與修正

// ❌ 錯誤:在子節點上調用
oldLi.replaceChild(newLi, oldLi); // TypeError

// ❌ 錯誤:參數順序反了
parent.replaceChild(oldLi, newLi); // 邏輯錯誤

// ✅ 正確:父節點調用,參數順序 (新, 舊)
parent.replaceChild(newLi, oldLi);

// ✅ 替換文本內容(更簡單)
oldLi.textContent = "新文本"; // 或 oldLi.firstChild.nodeValue = "新文本"

進階:批量替換與撤銷機制

// 批量替換所有匹配節點
function replaceAll(selector, newNodeFactory) {
  const nodes = document.querySelectorAll(selector);
  nodes.forEach(oldNode => {
    const newNode = newNodeFactory(oldNode);
    oldNode.parentNode.replaceChild(newNode, oldNode);
  });
}

// 可撤銷替換
const history = [];
function safeReplace(parent, oldNode, newNode) {
  history.push({ parent, oldNode, nextSibling: oldNode.nextSibling });
  parent.replaceChild(newNode, oldNode);
}

function undoLastReplace() {
  const last = history.pop();
  if (last) {
    last.parent.insertBefore(last.oldNode, last.nextSibling);
    last.parent.removeChild(last.parent.querySelector(newNode.selector)); // 簡化
  }
}

現代替代方案

  • oldNode.replaceWith(...newNodes):ChildNode 方法,支持多節點替換,語法更直觀
  • outerHTML 重賦值:簡單但會破壞引用與事件
  • 虛擬 DOM 框架(React/Vue)自動完成高效替換

掌握 replaceChild 的父節點視角與節點保留特性,是精通原生 DOM 操作的標誌性技能。

copyright © 萬盛學電腦網 all rights reserved