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!
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:… while the following are not OK:
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.