How to Clear Text Selection using JavaScript

Borislav Hadzhiev

Last updated: Jan 12, 2023
2 min


# 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.

<!DOCTYPE html> <html lang="en"> <head> <title></title> <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.

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

clear text selection using javascript

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.