Question

Let's say I highlight some text on the page using my mouse. How can I remove all highlighted text using JavaScript?

Thank you.

Was it helpful?

Solution

I've understood the question a bit differently. I believe you want to know how to delete the selected text from the document, in which case you could use:

function deleteSelection() {
    if (window.getSelection) {
        // Mozilla
        var selection = window.getSelection();
        if (selection.rangeCount > 0) {
            window.getSelection().deleteFromDocument();
            window.getSelection().removeAllRanges();
        }
    } else if (document.selection) {
        // Internet Explorer
        var ranges = document.selection.createRangeCollection();
        for (var i = 0; i < ranges.length; i++) {
            ranges[i].text = "";
        }
    }
}

If you just want to clear the highlight itself, and not remove the text being highlighted, the following should do the trick:

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

OTHER TIPS

IE 4 and old Netscape used to have a method to do just this... It's not longer proper (nor supported).

Your best guess would be to use Javascript to focus() on an object, and then blur() as well -- effectively like clicking away from the object.

document.getElementById("someObject").focus();
document.getElementById("someObject").blur();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top