How to replace selected text with html in content element?

With the contenteditable element, how can I replace the selected content with my own html?

+44
javascript jquery contenteditable
Jun 06 2018-11-06T00:
source share
2 answers

See here for jsFiddle to work: http://jsfiddle.net/dKaJ3/2/

function getSelectionHtml() { var html = ""; if (typeof window.getSelection != "undefined") { var sel = window.getSelection(); if (sel.rangeCount) { var container = document.createElement("div"); for (var i = 0, len = sel.rangeCount; i < len; ++i) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = container.innerHTML; } } else if (typeof document.selection != "undefined") { if (document.selection.type == "Text") { html = document.selection.createRange().htmlText; } } alert(html); } 

Code taken from Tim Down : Return HTML from user-selected text

+69
Jun 06 '11 at 12:45
source share

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>"); 
+47
Jun 06 2018-11-11T00:
source share



All Articles