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

浏览器兼容性

另见