How to replace selected text with html in a contenteditable element?

Frodik picture Frodik · Jun 6, 2011 · Viewed 59.4k times · Source

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

Answer

NakedBrunch picture NakedBrunch · Jun 6, 2011

See here for working jsFiddle: 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 a user-selected text