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 2015年7月.
setSelectionRange() は HTMLTextAreaElement インターフェイスのメソッドで、 <textarea> 要素における現在のテキスト選択の開始と終了の位置、およびオプションで方向を設定します。方向は、選択がどの方向に行われたかを示します。例えば、選択されたテキストの末尾から先頭に向かってユーザーがクリックしてドラッグしたことで選択が設定されたことを示します。さらに、 select および selectchange イベントが発生します。
このメソッドは HTMLTextAreaElement.selectionStart、HTMLTextAreaElement.selectionEnd、HTMLTextAreaElement.selectionDirection の各プロパティも更新します。
メモ:
<textarea> にフォーカスを当てると、 setSelectionRange() メソッドを使用してテキストの一部を選択できるようになります。 フォーカスを設定すると、 selectchange イベントも発行されます。
<textarea> 要素のテキストをすべて選択するには、 HTMLTextAreaElement.select() メソッドを使用します。
構文
setSelectionRange(selectionStart, selectionEnd)
setSelectionRange(selectionStart, selectionEnd, selectionDirection)
引数
selectionStart-
選択範囲の最初の文字のインデックス。 要素の値の長さを超えるインデックスを指定すると、値の末尾を指しているものとみなされます。 詳細は、
selectionStartプロパティを参照してください。 selectionEnd-
選択範囲の最後の文字の次の文字のインデックス。要素の値の長さを超えるインデックスを指定すると、値の末尾を指しているものとみなされます。
selectionEndがselectionStartより小さい場合、どちらもselectionEndの値として扱われます。 詳細な情報については、selectionEndプロパティを参照してください。 selectionDirection省略可-
"forward"、"backward"、または既定値の"none"で、選択が実行された方向を示します。 詳細は、selectionDirectionプロパティを参照してください。
返値
なし (undefined)。
例
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> |
ブラウザーの互換性
Loading…