--- title: HTMLInputElement.setSelectionRange() slug: Web/API/HTMLInputElement/setSelectionRange tags: - API - HTML DOM - HTMLInputElement - Method - Reference - Text Field Selection API translation_of: Web/API/HTMLInputElement/setSelectionRange ---
HTMLInputElement.setSelectionRange() 関数は{{HTMLElement("input")}}または、{{HTMLElement("textarea")}}要素に対して有効です。要素に対して任意の開始と末尾のポジションを設定することでテキストを選択状態にします。
更に、より新しいブラウザでは選択する方向をも考慮する必要があります。つまり、ユーザーがクリックした後ドラッグして選択状態にする際のドラッグの方向が、はじめからなのか、おしりからなのか、考慮するということです。
この関数はアップデートされ、HTMLInputElement.selectionStart, selectionEnd, and selectionDirectionプロパティを一度に呼び出し更新することができます。
Note that accordingly to the WHATWG forms spec selectionStart, selectionEnd properties and setSelectionRange method apply only to inputs of types text, search, URL, tel and password. Chrome, starting from version 33, throws an exception while accessing those properties and method on the rest of input types. For example, on input of type number: "Failed to read the 'selectionStart' property from 'HTMLInputElement': The input element's type ('number') does not support selection.".
element.setSelectionRange(selectionStart, selectionEnd [, selectionDirection]);
selectionEnd がselectionStartより小さい場合、両方の値はselectionEndとして扱われます。
selectionStartselectionEndselectionDirection {{optional_inline}}"forward""backward""none" 選択する際の方向が指定されていない時です。デフォルト値になります。サンプルの中のボタンをクリックすると、テキストボックスの3,4,5番目の文字が選択状態になります。 ("Mozilla"の"zil").
<input type="text" id="text-box" size="20" value="Mozilla"> <button onclick="selectText()">Select text</button>
function selectText() {
const input = document.getElementById('text-box');
input.focus();
input.setSelectionRange(2, 5);
}
{{EmbedLiveSample("Example")}}
| Specification | Status | Comment |
|---|---|---|
| {{SpecName("HTML WHATWG", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}} | {{Spec2("HTML WHATWG")}} | No change |
| {{SpecName("HTML5.1", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}} | {{Spec2("HTML5.1")}} | No change |
| {{SpecName("HTML5 W3C", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}} | {{Spec2("HTML5 W3C")}} | Initial definition |
{{Compat("api.HTMLInputElement.setSelectionRange")}}