[ACCEPTED]-Insert text in Javascript contenteditable div-contenteditable

Accepted answer
Score: 11

If all you need to do is insert HTML at 11 the current selection / insertion point, that 10 is doable. Off the top of my head (to get 9 you started):

In IE, use document.selection.createRange().pasteHTML(theNewHTML).

In 8 other browsers, you should be able to use 7 document.execCommand("InsertHTML", ...).

I've 6 used these kinds of techniques only in editable 5 iframes/documents, not divs, but these calls 4 should work if the div is focused, I believe.

As 3 another answer warned, it gets ugly if you 2 want finer-grained control, like inserting 1 text in other places.

Score: 7

The Range and Selection Objects

Use the selection and range objects. These contain all kinds 9 of information about the current selection, and 8 where it lies within the node tree.

Fair Warning: It's 7 not entirely impossible to do what you're 6 describing, but if you get very fancy, you'll 5 be in pretty deep water of browser quirks and incompatibilities. You're going 4 to have to do a lot of object detection, checking to make 3 sure you've got consistent values and methods. Incrementally 2 check all of your browsers as you develop. Good 1 luck!

Score: 1

Here's a cross-browser example, adapted 1 from this answer to work with iframes.

function pasteHtmlAtCaret(html, selectPastedContent, iframe) {
    var sel, range;
    var win = iframe ? iframe.contentWindow : window;
    var doc = win.document;
    if (win.getSelection) {
        // IE9 and non-IE
        sel = win.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // only relatively recently standardized and is not supported in
            // some browsers (IE9, for one)
            var el = doc.createElement("div");
            el.innerHTML = html;
            var frag = doc.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            var firstNode = frag.firstChild;
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                if (selectPastedContent) {
                    range.setStartBefore(firstNode);
                } else {
                    range.collapse(true);
                }
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if ( (sel = doc.selection) && sel.type != "Control") {
        // IE < 9
        var originalRange = sel.createRange();
        originalRange.collapse(true);
        sel.createRange().pasteHTML(html);
        if (selectPastedContent) {
            range = sel.createRange();
            range.setEndPoint("StartToStart", originalRange);
            range.select();
        }
    }
}
Score: 0

You can also use a round-about method using 9 insertImage. You insert a fake image (or 8 a small one) using the execCommand "insertImage", then 7 you use Javascript to replace the innerHTML 6 to add the text.

For example:

iFrame.focus()
iFrame.document.execCommand("insertImage", "", "fakeimage.jpg")
iFrame.document.body.innerHTML=iFrame.document.body.innerHTML.replace("<img src=\"fakeimage.jpg\">", "MY CUSTOM <b>HTML</b> HERE!")

Whereas iFrame 5 is equal to the id of the intended iFrame. Or, you 4 could use a DIV layer by using document.getElementById("IDofDIVlayer").innerHTML

Be 3 sure to focus before calling the execCommand, otherwise 2 it may not work in IE.

This method works 1 in IE too. Tested.

More Related questions