--- title: ChildNode.replaceWith() slug: orphaned/Web/API/ChildNode/replaceWith tags: - API - DOM - Method - Node - Reference translation_of: Web/API/ChildNode/replaceWith original_slug: Web/API/ChildNode/replaceWith ---
ChildNode.replaceWith() は親の子リストの ChildNode を、 {{domxref("Node")}} または {{domxref("DOMString")}} オブジェクトのセットに置換します。 {{domxref("DOMString")}} オブジェクトは {{domxref("Text")}} ノードと等価なノードとして挿入されます。
[Throws, Unscopable] void ChildNode.replaceWith((Node or DOMString)... nodes);
nodesreplaceWith() の使用var parent = document.createElement("div");
var child = document.createElement("p");
parent.appendChild(child);
var span = document.createElement("span");
child.replaceWith(span);
console.log(parent.outerHTML);
// "<div><span></span></div>"
ChildNode.replaceWith() はスコーピングに非対応replaceWith() メソッドは with 文でのスコーピングに対応していません。詳細は {{jsxref("Symbol.unscopables")}} をご覧ください。
with(node) {
replaceWith("foo");
}
// ReferenceError: replaceWith is not defined
以下のポリフィルで、 Internet Explorer 9 以降でも replaceWith() メソッドが利用できます。
function ReplaceWithPolyfill() {
'use-strict'; // For safari, and IE > 10
var parent = this.parentNode, i = arguments.length, currentNode;
if (!parent) return;
if (!i) // if there are no arguments
parent.removeChild(this);
while (i--) { // i-- decrements i and returns the value of i before the decrement
currentNode = arguments[i];
if (typeof currentNode !== 'object'){
currentNode = this.ownerDocument.createTextNode(currentNode);
} else if (currentNode.parentNode){
currentNode.parentNode.removeChild(currentNode);
}
// the value of "i" below is after the decrement
if (!i) // if currentNode is the first argument (currentNode === arguments[0])
parent.replaceChild(currentNode, this);
else // if currentNode isn't the first
parent.insertBefore(currentNode, this.nextSibling);
}
}
if (!Element.prototype.replaceWith)
Element.prototype.replaceWith = ReplaceWithPolyfill;
if (!CharacterData.prototype.replaceWith)
CharacterData.prototype.replaceWith = ReplaceWithPolyfill;
if (!DocumentType.prototype.replaceWith)
DocumentType.prototype.replaceWith = ReplaceWithPolyfill;
| 仕様書 | 策定状況 | コメント |
|---|---|---|
| {{SpecName('DOM WHATWG', '#dom-childnode-replacewith', 'ChildNode.replacewith()')}} | {{Spec2('DOM WHATWG')}} | 初期定義 |
{{Compat("api.ChildNode.replaceWith")}}