Selection: removeAllRanges()-Methode

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

Die Selection.removeAllRanges()-Methode entfernt alle Bereiche aus der Auswahl, sodass die Eigenschaften anchorNode und focusNode gleich null sind und nichts ausgewählt ist. Wenn diese Methode aufgerufen wird, wird ein selectionchange-Ereignis im Dokument ausgelöst.

Hinweis: Diese Methode ist ein Alias für die Selection.empty()-Methode.

Syntax

js
removeAllRanges()

Parameter

Keine.

Rückgabewert

Keiner (undefined).

Beispiele

Dieses Beispiel zeigt eine Nachricht an, wenn etwas auf der Seite ausgewählt ist oder nicht. Es tut dies, indem es dem Dokument auf das selectionchange-Ereignis lauscht. Es gibt auch eine Schaltfläche, die jede Auswahl löscht, indem sie Selection.removeAllRanges() aufruft. Wenn dies geschieht, wird die Auswahl geändert und die Nachricht wird aktualisiert.

html
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse laoreet
  urna eget sapien venenatis, eget facilisis diam mattis.
</p>
<button>Clear selection</button>
<pre id="log"></pre>
js
const log = document.getElementById("log");

// The selection object is a singleton associated with the document
const selection = document.getSelection();

// Logs if there is a selection or not
function newSelectionHandler() {
  if (selection.rangeCount !== 0) {
    log.textContent = "Some text is selected.";
  } else {
    log.textContent = "No selection on this document.";
  }
}

document.addEventListener("selectionchange", () => {
  newSelectionHandler();
});

newSelectionHandler();

// The button cancel all selection ranges
const button = document.querySelector("button");
button.addEventListener("click", () => {
  selection.removeAllRanges();
});

Spezifikationen

Specification
Selection API
# dom-selection-removeallranges

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
removeAllRanges

Legend

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

Full support
Full support

Siehe auch