Chrome execCommand "insertHTML" inserts a range outside of a node when there is a caret inside it

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

There are no problems in 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 play: Place the carriage at some point in the word “text,” then press the “i” key to insert an empty range in the current selection.

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

Example:

When you press the i key in the middle of a 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.

+6
source share
2 answers

You can make the contenteditable attribute of the span element false. To achieve your expectation, you need to move the last two lines outside the if-state. Here he 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) }); 
+1
source

It works?

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

instead of this:

 document.execCommand('insertHtml', null, node); 
0
source

Source: https://habr.com/ru/post/949026/


All Articles