HTMLInputElement.select()

HTMLInputElement.select() メソッドは、<textarea> 要素またはテキストフィールドを含む <input> 要素内のすべてのテキストを選択します。

構文

element.select();

この例のボタンをクリックすると、 <input> 要素内のすべてのテキストが選択されます。

HTML

<input type="text" id="text-box" size="20" value="Hello world!">
<button onclick="selectText()">テキストを選択</button>

JavaScript

function selectText() {
  const input = document.getElementById('text-box');
  input.focus();
  input.select();
}

結果

メモ

element.select() を呼び出しても、入力欄がフォーカスを得るとは限りませんので、よく HTMLElement.focus と一緒に使われます。

これに対応していないブラウザーでは、 HTMLInputElement.setSelectionRange() の引数に 0 と入力値の長さを指定して呼び出すことで置き換えることができます。

<input onClick="this.select();" value="Sample Text" />
<!-- equivalent to -->
<input onClick="this.setSelectionRange(0, this.value.length);" value="Sample Text" />

仕様書

Specification
HTML Standard
# dom-textarea/input-select

ブラウザーの互換性

BCD tables only load in the browser

関連情報