Last updated: Mar 5, 2024
Reading time·2 min
To clear the text selection:
window.getSelection()
method to get a Selection
object.removeAllRanges()
method on the result.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>bobbyhadz.com</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(); });
We used the
window.getSelection()
method to get a Selection
object that represents the selected text by the
user.
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.
If I load the example from the snippet above, select some of the text and click on the button, the selection gets cleared.
You can learn more about the related topics by checking out the following tutorials: