Element.replaceWith()

Element.replaceWith() メソッドは、この Element を親の子リストの中で一連の Node または DOMString オブジェクトに置換します。 DOMString オブジェクトは Text ノードと等価なノードとして挿入されます。

構文

replaceWith(...nodes)

引数

nodes

一連の Node または DOMString オブジェクトで置換します。

例外

replaceWith() の使用

const div = document.createElement("div");
const p = document.createElement("p");
div.appendChild(p);
const span = document.createElement("span");

p.replaceWith(span);

console.log(div.outerHTML);
// "<div><span></span></div>"

replaceWith() はスコーピングに非対応

replaceWith() メソッドは with 文でのスコーピングに対応していません。詳細は Symbol.unscopables をご覧ください。

with(node) {
  replaceWith("foo");
}
// ReferenceError: replaceWith is not defined

仕様書

Specification
DOM Standard
# ref-for-dom-childnode-replacewith①

ブラウザーの互換性

BCD tables only load in the browser

関連情報