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 2015年7月.
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> | 
ブラウザーの互換性
Loading…