locked
Add element to contenteditable div

    Question

  • Hello,

    I'm trying to add a span into the contents of an editable div

    <div id="contentBox" contenteditable="true" onkeypress="return keypress();"><span>a</span><span>b</span><span>c</span></div>

    function keypress(e) {

        var newSpan = document.createElement('span');
        newSpan.innerText = 'X';
     
        var newRange = document.selection.createRange();
        newRange.pasteHTML(newSpan.outerHTML)

        return false;
    }

    The resulting HTML is

    <span>a<span>X</span></span><span>b</span>...

    what I want is the newly inserted span to be inserted after the currently selected element and not nested inside it.

    <span>a</span><span>X</span><span>b</span>

    How am I able to do this?

    Thank you very much

    Saturday, October 27, 2012 1:28 AM