HTMLInputElement: select() メソッド

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.

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

構文

js
select()

引数

なし。

返値

なし (undefined)。

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

HTML

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

JavaScript

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

結果

メモ

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

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

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

仕様書

Specification
HTML
# dom-textarea/input-select

ブラウザーの互換性

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
select

Legend

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

Full support
Full support

関連情報