Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. HTMLInputElement
  4. selectionEnd

HTMLInputElement: selectionEnd property

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⁩.

TheselectionEnd property of theHTMLInputElement interface is a number that represents the end index of the selected text. That is, it represents the index of the characterimmediately following the selection. Likewise, when there is no selection, this returns the offset of the character immediately following the current text input cursor position.

Note:According to theWHATWG forms specselectionEnd property applies only to inputs of types text, search, URL, tel, and password. In modern browsers, throws an exception while settingselectionEnd property on the rest of input types. Additionally, this property returnsnull while accessingselectionEnd property on non-text input elements.

IfselectionEnd is less thanselectionStart, then both aretreated as the value ofselectionEnd.

Value

A non-negative number.

Examples

HTML

html
<!-- using selectionEnd on non text input element --><label for="color">selectionStart property on type=color</label><input type="color" /><!-- using selectionEnd on text input element --><fieldset>  <legend>selectionEnd property on type=text</legend>  <label for="pin">Input PIN</label>  <input type="text" value="impossible PIN: 102-12-145" />  <button type="button">PIN correction</button></fieldset>

JavaScript

js
const colorEnd = document.getElementById("color");const text = document.querySelector("#pin");const pinBtn = document.querySelector("#pin-btn");const validPinChecker = /^\d{3}-\d{2}-\d{3}/g;const selectionEnd = text.value.length;const selectedText = text.value.substring(text.selectionStart, selectionEnd);pinBtn.addEventListener("click", () => {  const correctedText = selectedText.replace(validPinChecker, "");  text.value = correctedText;});// open browser console to verify outputconsole.log(colorEnd.selectionEnd); // Output : null

Result

Specifications

Specification
HTML
# dom-textarea/input-selectionend

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp