Within a Contenteditable I try to change something during runtime. To replace the text with an element, so to speak. Whenever I replace the text, the caret-position resets to 0, my p-tag consists of many other elements like b, i, span and sometimes there is also a . If I replace the with a , the caret position is reset to the beginning. I simply lack a logical approach how to get for example the new caret position behind the new element. I think I already have most of the topics through here on this topic. Therefore I will now ask my first question here.
JSFidle: https://jsfiddle.net/eLv6p9kj/3/
Code JS:
function clickFunctionMouse(){
let text = $("#pelement").html();
//Replace the text with a image.
text = text.replace('<span>Text <b>sample</b><span>', '<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png">')
//Setting new HTML to Element. But how to get Caret-Position of the new Element?
$("#pelement").html(text);
}
$('#pelement').on("input", clickFunctionMouse);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
To show my problem, dont edit the text inside the span element..
<p contenteditable="true" id="pelement"><b>Hello</b> How are <i>you</i> <span>Text <b>sample</b><span> I dont know what else I could write <b>here!</b></p>
Many thanks in advance for the help from rainy Germany and good night.