Node: replaceChild() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Node 介面的 replaceChild() 方法用於替換給定(父)節點內的子節點。

語法

js
replaceChild(newChild, oldChild)

引數

newChild

用於替換 oldChild 的新節點。

警告: 如果新節點已存在於 DOM 的其他位置,它將首先從該位置移除。

oldChild

要被替換的子節點。

注意: 引數順序,在前在後,很不尋常。Element.replaceWith(),僅適用於元素節點,可能更易讀和使用。

返回值

被替換的 Node。這與 oldChild 是同一個節點。

異常

HierarchyRequestError DOMException

當違反 DOM 樹約束時丟擲,即發生以下任一情況:

NotFoundError DOMException

如果 oldChild 的父節點不是當前節點,則丟擲此異常。

示例

js
// Given:
// <div>
//  <span id="childSpan">foo bar</span>
// </div>

// Create an empty element node
// without an ID, any attributes, or any content
const sp1 = document.createElement("span");

// Give it an id attribute called 'newSpan'
sp1.id = "newSpan";

// Create some content for the new element.
const sp1_content = document.createTextNode("new replacement span element.");

// Apply that content to the new element
sp1.appendChild(sp1_content);

// Build a reference to the existing node to be replaced
const sp2 = document.getElementById("childSpan");
const parentDiv = sp2.parentNode;

// Replace existing node sp2 with the new span element sp1
parentDiv.replaceChild(sp1, sp2);

// Result:
// <div>
//   <span id="newSpan">new replacement span element.</span>
// </div>

規範

規範
DOM
# dom-node-replacechild

瀏覽器相容性

另見