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> 元素或者一个带有 text 字段的 <input> 元素里的所有内容。

语法

element.select()

示例

点击这个例子的按钮以选中所有在<input>元素中的文字

HTML

html
<input type="text" id="text-box" size="20" value="Hello world!" />
<button onclick="selectText()">Select text</button>

JavaScript

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

结果

注意

调用 element.select() 并不一定会使得该 input 元素被 focused,所以它经常和 HTMLElement.focus() 一起使用。

规范

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

相关链接