To get the selected HTML, you can use the function that I wrote for this question . To replace the selection with your own HTML, you can use this function . Here is the version of the replacer function that inserts an HTML string instead of a DOM node:
function replaceSelectionWithHtml(html) { var range; if (window.getSelection && window.getSelection().getRangeAt) { range = window.getSelection().getRangeAt(0); range.deleteContents(); var div = document.createElement("div"); div.innerHTML = html; var frag = document.createDocumentFragment(), child; while ( (child = div.firstChild) ) { frag.appendChild(child); } range.insertNode(frag); } else if (document.selection && document.selection.createRange) { range = document.selection.createRange(); range.pasteHTML(html); } } replaceSelectionWithHtml("<b>REPLACEMENT HTML</b>");
Tim Down Jun 06 2018-11-11T00: 00Z
source share