HTMLInputElement: selectionEnd-Eigenschaft

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.

Die selectionEnd-Eigenschaft des HTMLInputElement-Interfaces ist eine Zahl, die das End-Index des ausgewählten Textes darstellt. Wenn keine Auswahl besteht, gibt sie den Offset des Zeichens unmittelbar nach der aktuellen Cursorposition im Texteingabefeld zurück.

Hinweis: Gemäß der WHATWG-Formularspezifikation gilt die selectionEnd-Eigenschaft nur für Eingaben der Typen Text, Suche, URL, Tel und Passwort. In modernen Browsern wird eine Ausnahme ausgelöst, wenn die selectionEnd-Eigenschaft bei anderen Eingabetypen gesetzt wird. Zusätzlich gibt diese Eigenschaft null zurück, wenn auf die selectionEnd-Eigenschaft von Nicht-Texteingabeelementen zugegriffen wird.

Wenn selectionEnd kleiner ist als selectionStart, werden beide als der Wert von selectionEnd behandelt.

Wert

Eine nicht negative Zahl.

Beispiele

HTML

html
<!-- using selectionEnd on non text input element -->
<label for="color">selectionStart property on type=color</label>
<input id="color" 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" id="pin" value="impossible PIN: 102-12-145" />
  <button id="pin-btn" 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 output
console.log(colorEnd.selectionEnd); // Output : null

Ergebnis

Spezifikationen

Specification
HTML
# dom-textarea/input-selectionend

Browser-Kompatibilität

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
selectionEnd

Legend

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

Full support
Full support

Siehe auch