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

View in English Always switch to English

Selection: addRange() メソッド

Baseline 広く利用可能

この機能は広く実装されており、多くのバージョンの端末やブラウザーで動作します。2015年7月以降、すべてのブラウザーで利用可能です。

Selection.addRange() メソッドは、RangeSelection に追加します。

構文

js
addRange(range)

引数

range

この Selection に追加する Range オブジェクト。

返値

なし (undefined)。

複数範囲の選択に対応しているのは Firefox のみである点に注意してください。この例では、他のブラウザーで、選択範囲にすでに 1 つ含まれている場合、新しい範囲を追加することはできません。

HTML

html
<p>
  I <strong>insist</strong> that you <strong>try</strong> selecting the
  <strong>strong words</strong>.
</p>
<button>Select strong words</button>

JavaScript

js
let button = document.querySelector("button");

button.addEventListener("click", () => {
  const selection = window.getSelection();
  const strongElems = document.getElementsByTagName("strong");

  if (selection.rangeCount > 0) {
    selection.removeAllRanges();
  }

  for (const node of strongElems) {
    const range = document.createRange();
    range.selectNode(node);
    selection.addRange(range);
  }
});

結果

仕様書

仕様書
Selection API
# dom-selection-addrange

ブラウザーの互換性

関連情報

  • 所属先のインターフェイスである Selection