The Selection.empty()
method removes all ranges from the selection, leaving the anchorNode
and focusNode
properties equal to null
and nothing selected. When this method is called, a selectionchange
event is fired at the document.
This example displays a message when something is selected on the page or not. It does this by listening to the selectionchange
event on the document. There also is a button that clears any selection by calling Selection.empty()
. When this happens, the selection is changed and the message is updated.
<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>
const log = document.getElementById("log");
const selection = document.getSelection();
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();
const button = document.querySelector("button");
button.addEventListener("click", () => {
selection.empty();
});