0

I want to highlight the user selected Text. I cant use the JQuery Based API for Highlight since I want user specific highlight.

Here is how my code looks like.

var range = window.getSelection().getRangeAt(0);
var sel = window.getSelection();
range.setStart( sel.anchorNode, sel.anchorOffset );
range.setEnd(sel.focusNode,sel.focusOffset);
highlightSpan = document.createElement("span");
highlightSpan.setAttribute("style","background-color: yellow; ");
highlightSpan.appendChild(range.extractContents()); 
range.insertNode(highlightSpan)    

This works in normal scenarios but if I select some text in different paragraphs the extractContents API will validate the HTML returned and put additional tags to make it valid HTML. I want the exact HTML that was selected without the additional validating that javascript did.

Is there any way this can be done?

Regards, Tina

Tina Agrawal
  • 616
  • 9
  • 16
  • Duplicate: http://stackoverflow.com/questions/2584301/getselection-surroundcontents-across-multiple-tags http://stackoverflow.com/questions/2582831/highlight-the-text-of-the-dom-range-element , http://stackoverflow.com/questions/1622629/javascript-highlight-selected-range-button – Tim Down May 05 '10 at 09:02

1 Answers1

0

This has come up a few times:

How can I highlight the text of the DOM Range object? Javascript Highlight Selected Range Button

Here's my answer:

The following should do what you want. In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again.

function highlight(colour) {
    var range, sel;
    if (window.getSelection) {
        // Non-IE case
        sel = window.getSelection();
        if (sel.getRangeAt) {
            range = sel.getRangeAt(0);
        }
        document.designMode = "on";
        if (range) {
            sel.removeAllRanges();
            sel.addRange(range);
        }
        // Use HiliteColor since some browsers apply BackColor to the whole block
        if ( !document.execCommand("HiliteColor", false, colour) ) {
            document.execCommand("BackColor", false, colour);
        }
        document.designMode = "off";
    } else if (document.selection && document.selection.createRange) {
        // IE case
        range = document.selection.createRange();
        range.execCommand("BackColor", false, colour);
    }
}
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536