Node: replaceChild() 方法
Node 接口的 replaceChild() 方法用于替换给定(父)节点内的子节点。
语法
js
replaceChild(newChild, oldChild)
参数
注意: 参数顺序,新在前旧在后,很不寻常。Element.replaceWith(),仅适用于元素节点,可能更易读和使用。
返回值
被替换的 Node。这与 oldChild 是同一个节点。
异常
HierarchyRequestErrorDOMException-
当违反 DOM 树约束时抛出,即发生以下任一情况:
- 如果
oldChild的父节点不是Document、DocumentFragment或Element。 - 如果用
newChild替换oldChild会导致循环,即newChild是该节点的祖先。 - 如果
newChild不是DocumentFragment、DocumentType、Element或CharacterData。 - 如果当前节点是
Text节点,且其父节点是Document。 - 如果当前节点是
DocumentType节点,且其父节点不是Document,因为文档类型(doctype)应该始终是文档(document)的直接后代。 - 如果父节点是
Document节点,且newChild是一个包含多个Element子节点或包含Text子节点的DocumentFragment。 - 如果用
newChild替换oldChild会导致Document包含多个Element子节点。 - 如果用
newChild替换oldChild会导致Element节点出现在DocumentType节点之前。
- 如果
NotFoundErrorDOMException-
如果
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 |
浏览器兼容性
加载中…