3

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?

9
  • There are a lot of cross-browser hassles with this stuff. You might want to look at a library called Rangy that helps smooth them over, and offers highlighting features as in this demo. (I have no affiliation with Rangy.) Commented Nov 10, 2011 at 10:13
  • Tricky. I've seen this asked before and there's no easy way. Commented Nov 10, 2011 at 10:24
  • Re Rangy, I'm the author, and it won't really help you with this (yet: I'm working on it), unless you used a CSS class to do the highlighting instead, in which case you could use the CSS class applier module: code.google.com/p/rangy/wiki/CSSClassApplierModule Commented Nov 10, 2011 at 10:26
  • @T.J.Crowder Can I use Rangy library with UIWebView on ios4.2 or later platform? Commented Nov 12, 2011 at 13:33
  • Yes, Rangy works in Mobile Safari and in UIWebView. Commented Nov 12, 2011 at 16:41

3 Answers 3

8

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;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Tim, this is amazing. For some reason the unhighlight fn was giving me an error when it tries to create a new Colour object (in the wild). No worries though, I'm not particular that the unhighlight color matches the highlight color; I'd rather just get rid of all highlights. So, to get around it, I just removed the condition "if(bg && colour.equals(new Colour(bg)))". Thanks.
@Tim Down Could you please check this.. In demo the button is not highlighting. Please check. It would be great help.
@SoI: I think I missed you comment. Which browser is showing the problem?
@Tim Down: rather than just get rid of all highlights can we unhighlight any specific selected highlighted text area ?
Yes we can. Use the solution posted in stackoverflow.com/questions/1335252/…
4

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.

5 Comments

I think you misunderstand my question. I want to do it dynamically using javascript.
@PhoenixJon this will be dynamic. It'll change the background color of only the text that is selected. Not using JavaScript, but it'll work like you want it to.
@Amaan Thanks for your comment. Er.. What i want is when i select the text and press "highlight" button, then the selected text remains highlighted. And again when i pressed "remove" button, highlighted text becomes normal text. Something like this..
Thanks. I want to know when execCommand is executed, the span tag is added? If so, tag name or id exists in that tag? or only set background color?
The last time I checked, the command wraps a <span> tag around the range with the appropriate style applied.
-1

Use

sel.removeAllRanges()

2 Comments

and i dont think u'll need to do anything else . all the background color will be restored automatically .
He's already using removeAllRanges. The issue is that he's executed the hilitecolor command on a range, and so it now has that, and he wants to remove it later.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.