0

I have this code with which I put selected text inside a span that gives it a background-color with CSS. When I try to 'mark' text from two different divs, or text which is inside any two tags, I get an error: Uncaught Error: BAD_BOUNDARYPOINTS_ERR: DOM Range Exception 1

This is my code:

function highlightSelection()   {
var selection;



//Get the selected stuff
    if(window.getSelection) 
        selection = window.getSelection();
    else if(typeof document.selection!="undefined")
        selection = document.selection;

    //Get a the selected content, in a range object
    var range = selection.getRangeAt(0);

    //If the range spans some text, and inside a tag, set its css class.
    if(range && !selection.isCollapsed)
    {
            var span = document.createElement('span');
            span.className = 'highlight-green';
            range.surroundContents(span);
    }
}

The highlightSelection() is called with onmouseup event. Thanks ahead!

Tomcatom
  • 365
  • 3
  • 6
  • 16

1 Answers1

1

The surroundContents() method of Range only works when the contents of the Range can be surrounded within a single node. It's fairly intuitive with examples. So, where curly braces denote range boundaries, the following are OK:

One {two} three
One {two <b>three</b> four} five

... while the following are not OK:

One {two <b>three} four</b> five
One <b>two {three</b> <i>four} five</i>

Insetad, I suggest using document.execCommand() for applying a background colour to the selection, as this will deal with all this stuff for you. I've provided code to do this on Stack Overflow before.

If you need to apply a class instead, you could use the CSS class applier module of my Rangy library.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thanks for the reply. Iv'e now tried applying your code (I just found that SO discussion, I take the blame for insufficient research) but nothing happens. Iv'e created a JSfiddle [here](http://jsfiddle.net/9gXWt/), could we continue this over chat? Thanks! – Tomcatom Nov 30 '12 at 15:19