Chrome execCommand 'insertHTML' inserts span outside of node when caret is inside it
Asked Answered
A

2

6

My task is to insert an empty span node within a contentEditable div at current caret position.

The following gives me no problems on Firefox 22.0:

HTML

<div class="parent" contentEditable=true>
    <div>text</div>
</div>

Javascript

$('.parent').on("keyup", function(e){
    if (e.which == 73) {
       node = '<span class="new"></span>';
       document.execCommand('insertHtml', null, node);
   }
});

To reproduce: Place caret at some point of the word 'text', then press 'i' key to insert an empty span at current selection.

See: http://jsfiddle.net/amirisnino/pZecx/2/

Example:

When pressing 'i' key in the middle of the word

Expected result:

<div class="parent" contentEditable=true>
    <div>tei<span class="new"></span>xt</div>
</div>

What happens instead?

<div class="parent" contentEditable=true>
    <div>teixt</div>
    <span class="new"></span>
    <div><br></div>
</div>

Any help with this would be greatly appreciated. Thank you in advance.

Atomics answered 9/7, 2013 at 15:9 Comment(0)
S
2

You can make the contenteditable attribute of span element as false. In order to achieve your expectation, you have to move the last two lines outside of the if-condition. Here it is:

$('.parent').on("keyup", function(e){
    if (e.which == 73) {
         node = '<span contenteditable="false" class="new"></span>';
         document.execCommand('insertHtml', null, node);
       }
       content = $(this).html()
       $('.result').text(content)

});
Soble answered 3/9, 2017 at 4:28 Comment(0)
C
0

Does this work?

$('.parent div').append(node);

instead of this:

document.execCommand('insertHtml', null, node);
Caro answered 4/7, 2014 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.