JSFiddle - React, Tailwind, and code Playground
HTML
Click on 'New Text' if the focus is not there and place the cursor at the end of the text. Then click on the replace link
<div id="test" contenteditable=true>
Some text
<font color="blue">Text to be replaced</font>
... and more text
</div>
<a id="replace" href="javascript:void(null);">replace</a>
<br />
After clicking replace you ll notice that focus remains on the contenteditable div but cursor moves to the begining of the text.
<br />
Cursor should come at the end of the replacing html i.e. after the span tag
CSS
#test{
padding:2px;
border:1px solid yellow;
}
JavaScript
function placeCaretAfter(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.setStartAfter(el);
range.collapse(true);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
$('#test').focus();
$('#replace').on({
mousedown: function (event) {
event.preventDefault();
},
click: function () {
var span = document.createElement("span");
span.style.color = "red";
span.setAttribute('contenteditable', 'true');
span.innerHTML = "New Text";
$('#test').find('font').replaceWith(span);
placeCaretAfter(span);
}
});