Node.replaceChild()
method replaces a child node within the given (parent) node.
Note the idiosyncratic argument order (new before old).
ChildNode.replaceWith()
may be easier to read and use.
parentNode.replaceChild(newChild, oldChild);
oldChild
. If it already exists in the DOM, it is first removed.
The child to be replaced.
The returned value is the replaced node. This is the same node as
oldChild
.
// Given:
// <div>
// <span id="childSpan">foo bar</span>
// </div>
// Create an empty element node
// without an ID, any attributes, or any content
var sp1 = document.createElement("span");
// Give it an id attribute called 'newSpan'
sp1.id = "newSpan";
// Create some content for the new element.
var 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
var sp2 = document.getElementById("childSpan");
var 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
The definition of 'Node: replaceChild' in that specification. |
实时标准 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
replaceChild
|
Chrome 1 | Edge 12 | Firefox 1 | IE 9 | Opera 7 | Safari 1.1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 |
完整支持
节点
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
Document
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
文本
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument