JavaScript Set Window selection

Richard J. Ross III picture Richard J. Ross III · May 31, 2011 · Viewed 18.3k times · Source

In JavaScript, there is a method window.getSelection(), that lets me get the current selection that the user has made.

Is there a corresponding function, something like window.setSelection(), that will let me set, or clear, the current selection?

Answer

Tim Down picture Tim Down · May 31, 2011

Clearing the selection in all major browsers:

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

Selecting content requires use of DOM Range and Selection objects in most browsers and TextRange objects in IE < 9. Here's a simple cross-browser example that selects the contents of a particular element:

function selectElement(element) {
    if (window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
        var range = document.createRange();
        range.selectNodeContents(element);
        sel.addRange(range);
    } else if (document.selection) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(element);
        textRange.select();
    }
}