Is there a function to deselect all text using JavaScript?

NoodleOfDeath picture NoodleOfDeath · Jul 3, 2011 · Viewed 69.3k times · Source

Is there a function in javascript to just deselect all selected text? I figure it's got to be a simple global function like document.body.deselectAll(); or something.

Answer

Ankur picture Ankur · Jul 3, 2011

Try this:

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

This will clear a selection in regular HTML content in any major browser. It won't clear a selection in a text input or <textarea> in Firefox.