Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove highlight added to selected text using JavaScript?

I highlighted selected text using JavaScript with the following code:

var sel = window.getSelection();
if(!sel.isCollapsed) {
    var range = sel.getRangeAt(0);
    sel.removeAllRanges();
    document.designMode = "on";
    sel.addRange(range);
    document.execCommand("HiliteColor", false, "#ffffcc");
    sel.removeAllRanges();
    document.designMode = "off";
}

How do I then remove the highlighted color and restore the text?

like image 421
PhoenixJon Avatar asked Jun 25 '26 05:06

PhoenixJon


2 Answers

Here's some code to add and remove highlights. It's too long to post here practically, so I've made a demo and posted a snippet below. It's not quite ideal because the unhighlight() function doesn't remove <span> elements inserted by the highlight command, but with a little care this would be a possible addition.

Live demo: http://jsfiddle.net/timdown/Bvd9d/

Code snippet:

function unhighlight(node, colour) {
    if (!(colour instanceof Colour)) {
        colour = new Colour(colour);
    }

    if (node.nodeType == 1) {
        var bg = node.style.backgroundColor;
        if (bg && colour.equals(new Colour(bg))) {
            node.style.backgroundColor = "";
        }
    }
    var child = node.firstChild;
    while (child) {
        unhighlight(child, colour);
        child = child.nextSibling;
    }
}
like image 63
Tim Down Avatar answered Jun 26 '26 20:06

Tim Down


You could use CSS instead:

<style>
    ::selection {background-color: #ffffcc;}
</style>

EDIT: Update in response to comment and clarification

<script type="text/javascript">
    var spans = document.getElementsByTagName('span'), i;
    for( i=0; i<spans.length; i++) {
       if( spans[i].style.backgroundColor == "#ffffcc") {
           // Two alternatives. This:
           spans[i].style.backgroundColor = "transparent";
           // OR this, if spans contain only text:
           spans[i].parentNode.replaceChild(spans[i].firstChild,spans[i]);
           i--;
           // End alternatives - only include i-- in the second one
       }
    }
</script>

Although, this fails in some browsers (I think it's Firefox) where the element style is changed to the computed style.

like image 34
Niet the Dark Absol Avatar answered Jun 26 '26 20:06

Niet the Dark Absol