Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would suggest using <code>document</code>'s or the <code>TextRange</code>'s <code>execCommand</code> method, which is built for just such a purpose, but is usually used in editable documents. Here's the answer I gave to a similar question:</p> <p>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.</p> <p><strong>UPDATE</strong></p> <p>Fixed to work in IE 9.</p> <p><strong>UPDATE 12 September 2013</strong></p> <p>Here's a link detailing a method for removing highlights created by this method:</p> <p><a href="https://stackoverflow.com/a/8106283/96100">https://stackoverflow.com/a/8106283/96100</a></p> <pre><code>function makeEditableAndHighlight(colour) { var range, sel = window.getSelection(); if (sel.rangeCount &amp;&amp; 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"; } function highlight(colour) { var range; if (window.getSelection) { // IE9 and non-IE try { if (!document.execCommand("BackColor", false, colour)) { makeEditableAndHighlight(colour); } } catch (ex) { makeEditableAndHighlight(colour) } } else if (document.selection &amp;&amp; document.selection.createRange) { // IE &lt;= 8 case range = document.selection.createRange(); range.execCommand("BackColor", false, colour); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload