HTMLTextAreaElement: setSelectionRange() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

setSelectionRange()HTMLTextAreaElement インターフェイスのメソッドで、 <textarea> 要素における現在のテキスト選択の開始と終了の位置、およびオプションで方向を設定します。方向は、選択がどの方向に行われたかを示します。例えば、選択されたテキストの末尾から先頭に向かってユーザーがクリックしてドラッグしたことで選択が設定されたことを示します。さらに、 select および selectchange イベントが発生します。

このメソッドは HTMLTextAreaElement.selectionStartHTMLTextAreaElement.selectionEndHTMLTextAreaElement.selectionDirection の各プロパティも更新します。

メモ: <textarea> にフォーカスを当てると、 setSelectionRange() メソッドを使用してテキストの一部を選択できるようになります。 フォーカスを設定すると、 selectchange イベントも発行されます。

<textarea> 要素のテキストをすべて選択するには、 HTMLTextAreaElement.select() メソッドを使用します。

構文

js
setSelectionRange(selectionStart, selectionEnd)
setSelectionRange(selectionStart, selectionEnd, selectionDirection)

引数

selectionStart

選択範囲の最初の文字のインデックス。 要素の値の長さを超えるインデックスを指定すると、値の末尾を指しているものとみなされます。 詳細は、 selectionStart プロパティを参照してください。

selectionEnd

選択範囲の最後の文字の次の文字のインデックス。要素の値の長さを超えるインデックスを指定すると、値の末尾を指しているものとみなされます。 selectionEndselectionStart より小さい場合、どちらも selectionEnd の値として扱われます。 詳細な情報については、selectionEnd プロパティを参照してください。

selectionDirection 省略可

"forward""backward"、または既定値の "none" で、選択が実行された方向を示します。 詳細は、 selectionDirection プロパティを参照してください。

返値

なし (undefined)。

js
const textarea = document.getElementById("text-box");
const chars = textarea.textLength;
// 値が 10 文字以上の長さであれば
if (chars > 10) {
  // 内部のテキストの範囲を選択するには、要素にフォーカスを設定する必要がある
  textarea.focus();
  // テキストの先頭から 5 文字目と末尾から 5 文字目までの間を選択
  textarea.setSelectionRange(5, chars - 5);
} else {
  // それ以外の場合はすべてのテキストを選択
  textarea.select();
}

仕様書

Specification
HTML
# dom-textarea/input-setselectionrange-dev

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
setSelectionRange

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報