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
In browsers that support the "selection" and "range" stuff, you'll want to create a range object and then set its start/end. The Mozilla documentation for the "range" object has a lot of information.
Chrome doesn't support this, at least not with that API, and I bet Safari doesn't either.
edit — thanks to @Tim Down for noting that WebKit (Chrome & Safari) do indeed support this, which means my jsfiddle had a typo or something!
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();
}
}
Maybe this will do it:
window.selection.clear();
Crossbrowser version:
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}