window.getSelection()method returns a
Selectionobject, which represents the current text selection. To clear the selection, you can call the
removeAllRanges()method on the
document.execCommand()method can be used to execute a variety of commands on the document, including clearing the text selection. To clear the selection, you would call the
document.execCommand()method with the
// Clear text selection using the window.getSelection() method const selection = window.getSelection(); selection.removeAllRanges(); // Clear text selection using the document.execCommand() method document.execCommand("unselect");
Which method should I use to clear text selection?
window.getSelection() method is generally considered to be the better method for clearing text selection. This is because it is more explicit and less likely to cause unexpected results.