Selection: empty() 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.empty() Methode entfernt alle Bereiche aus der Auswahl, wodurch die Eigenschaften anchorNode und focusNode auf null gesetzt werden 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.removeAllRanges() Methode.

Syntax

js
empty()

Parameter

Keine.

Rückgabewert

Keiner (undefined).

Beispiele

Dieses Beispiel zeigt eine Nachricht an, wenn etwas auf der Seite ausgewählt oder nicht ausgewählt wird. Es erreicht dies, indem es auf das selectionchange Ereignis im Dokument hört. Es gibt auch einen Knopf, der jegliche Auswahl löscht, indem er Selection.empty() 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.empty();
});

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
empty() as alias of removeAllRanges()

Legend

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

Full support
Full support

Siehe auch