Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes. The following will do it in all major browsers, with an option to select the inserted content afterwards as requested in the comments (although this part is not implemented for IE &lt;= 8):</p> <p>Live demo: <a href="http://jsfiddle.net/bXsWQ/147/">http://jsfiddle.net/bXsWQ/147/</a></p> <p>Code:</p> <pre><code>function replaceSelection(html, selectInserted) { var sel, range, fragment; if (typeof window.getSelection != "undefined") { // IE 9 and other non-IE browsers sel = window.getSelection(); // Test that the Selection object contains at least one Range if (sel.getRangeAt &amp;&amp; sel.rangeCount) { // Get the first Range (only Firefox supports more than one) range = window.getSelection().getRangeAt(0); range.deleteContents(); // Create a DocumentFragment to insert and populate it with HTML // Need to test for the existence of range.createContextualFragment // because it's non-standard and IE 9 does not support it if (range.createContextualFragment) { fragment = range.createContextualFragment(html); } else { // In IE 9 we need to use innerHTML of a temporary element var div = document.createElement("div"), child; div.innerHTML = html; fragment = document.createDocumentFragment(); while ( (child = div.firstChild) ) { fragment.appendChild(child); } } var firstInsertedNode = fragment.firstChild; var lastInsertedNode = fragment.lastChild; range.insertNode(fragment); if (selectInserted) { if (firstInsertedNode) { range.setStartBefore(firstInsertedNode); range.setEndAfter(lastInsertedNode); } sel.removeAllRanges(); sel.addRange(range); } } } else if (document.selection &amp;&amp; document.selection.type != "Control") { // IE 8 and below range = document.selection.createRange(); range.pasteHTML(html); } } </code></pre> <p>Example:</p> <pre><code>replaceSelection('&lt;span&gt;&lt;font color="red"&gt;hoho&lt;/font&gt;&lt;/span&gt;', true); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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