replaceChild(newNode, oldNode) 是 父節點 的方法,用新節點替換舊子節點。理解「父節點視角」是正確使用的關鍵。
createElement、createTextNode、cloneNode)querySelector、children[index])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 重賦值:簡單但會破壞引用與事件掌握 replaceChild 的父節點視角與節點保留特性,是精通原生 DOM 操作的標誌性技能。