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 |
瀏覽器相容性
載入中…