このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

Element: replaceWith() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2018年4月⁩.

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

構文

js
replaceWith(param1) replaceWith(param1, param2) replaceWith(param1, param2, /* … ,*/ paramN) 

引数

param1, …, paramN

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

返値

なし (undefined)。

例外

HierarchyRequestError DOMException

階層の指定の位置にノードを挿入できなかったときに発生します。

replaceWith() の使用

js
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 をご覧ください。

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

仕様書

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

ブラウザーの互換性

関連情報