Is there a function to deselect all text using JavaScript?

Is there a function in javascript to simply deselect all selected text? I suppose it was a simple global function like document.body.deselectAll(); or something like that.

+48
javascript selection
Jul 03 '11 at 12:00
source share
3 answers

Try the following:

 function clearSelection() { if ( document.selection ) { document.selection.empty(); } else if ( window.getSelection ) { window.getSelection().removeAllRanges(); } } 

This will clear the selection in plain HTML content in any major browser. It will not clear the selection in text input or <textarea> in Firefox.

+80
Jul 03 2018-11-11T00:
source share

Here's a version that will clear any selection, including in text inputs and text areas:

Demo: http://jsfiddle.net/SLQpM/23/

 function clearSelection() { var sel; if ( (sel = document.selection) && sel.empty ) { sel.empty(); } else { if (window.getSelection) { window.getSelection().removeAllRanges(); } var activeEl = document.activeElement; if (activeEl) { var tagName = activeEl.nodeName.toLowerCase(); if ( tagName == "textarea" || (tagName == "input" && activeEl.type == "text") ) { // Collapse the selection to the end activeEl.selectionStart = activeEl.selectionEnd; } } } } 
+21
Feb 09 '13 at 12:44
source share

For Internet Explorer, you can use the empty method of the document.selection object:

document.selection.empty ();

For a cross-browser solution, see this answer:

Clear selection in Firefox

+5
Jul 03 '11 at 12:05
source share



All Articles