If you want to do some kind of highlighting of the current selection, using the built-in document.execCommand() is the easiest way. It works in all major browsers.
The following should do what you want on any selection, including ones spanning multiple elements. In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again.
UPDATE
Fixed to work in IE 9.
function highlightSelectionmakeEditableAndHighlight(colour) { var range, sel; sel if= (window.getSelection() {; if (sel.rangeCount //&& Non-IEsel.getRangeAt) case{ selrange = windowsel.getSelectiongetRangeAt(0); } if (seldocument.getRangeAt)designMode {= "on"; if (range) { range = sel.getRangeAtremoveAllRanges(0); sel.addRange(range); } // Use HiliteColor since document.designModesome =browsers "on"; apply BackColor to the whole block if (range!document.execCommand("HiliteColor", false, colour)) { seldocument.removeAllRangesexecCommand("BackColor", false, colour); } document.designMode = "off"; } function sel.addRangehighlightSelection(rangecolour); { var range; } if (window.getSelection) { // UseIE9 HiliteColorand sincenon-IE some browsers apply BackColor to the whole blocktry { if ( !document.execCommand("HiliteColor""BackColor", false, colour) ) { document.execCommand("BackColor", false, makeEditableAndHighlight(colour); } } catch (ex) { document.designMode = "off"; makeEditableAndHighlight(colour) } } else if (document.selection && document.selection.createRange) { // IE <= 8 case range = document.selection.createRange(); range.execCommand("BackColor", false, colour); } } document.onmouseup = function() { highlightSelection("red"); }; Live example: http://www.jsfiddle.net/timdown/eBqBU/http://jsfiddle.net/eBqBU/9/