How to Clear Text Selection using JavaScript

avatar

Borislav Hadzhiev

Sat Jan 08 20221 min read

banner

Photo by Tom Sodoge

Clear Text Selection using JavaScript #

To clear the text selection:

  1. Use the window.getSelection() method to get a Selection object.
  2. Call the removeAllRanges() method on the result.
  3. The removeAllRanges() method removes all ranges from the selection, leaving nothing selected.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style="margin-top: 100px"> Select some of this text and click on the button. </div> <button id="btn">Remove and console.log selection</button> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { // 👇️ log text selection console.log(window.getSelection()?.toString()); // ✅ Clear text selection window.getSelection()?.removeAllRanges(); });

We used the window.getSelection() method to get a Selection object that represents the selected text by the user.

If you call the toString() method on the object, a string containing the selected text is returned.

The getSelection method is very well supported, for more info check out the Browser compatibility table on MDN's docs.

If the method is called on an iframe that is not displayed, e.g. with display set to none, the method returns null in Firefox.

That's why we used the optional chaining (?.) operator to short-circuit if the the method returns a null value - this is completely optional.

The removeAllRanges method is also very widely supported.

The method removes all ranges from the user's selection, leaving nothing selected.

If I load the example from the snippet above, select some of the text and click on the button, the selection gets cleared.

Use the search field on my Home Page to filter through my more than 1,000 articles.