Range: surroundContents() メソッド

Range.surroundContents() メソッドは Range の内容を新しいノードに移動し、新しいノードを指定された範囲の先頭に配置します。

このメソッドは newNode.appendChild(range.extractContents()); range.insertNode(newNode) とほぼ同じです。 囲んだ後の range の境界点は newNode を含みます。

ただし、RangeText でないノードをその境界点の 1 つだけで分割した場合は例外が発生します。つまり、上記の代案とは異なり、部分的に選択されたノードがある場合、それらのノードは複製されず、代わりに処理が失敗します。

構文

js
surroundContents(newParent)

引数

newParent

コンテンツを囲むNode です。

返値

なし (undefined)。

HTML

html
<span class="header-text">Put this in a headline</span>

JavaScript

js
const range = document.createRange();
const newParent = document.createElement("h1");

range.selectNode(document.querySelector(".header-text"));
range.surroundContents(newParent);

結果

仕様書

Specification
DOM Standard
# dom-range-surroundcontents

ブラウザーの互換性

BCD tables only load in the browser

関連情報