JSFiddle - React, Tailwind, and code Playground
HTML
<div id="ro">
</div>
<br>
<div id="editable" contenteditable="true">
<b><i>Hel</i><i>l</i></b><i><b>o World!</b></i><i>Hel</i><i>lo</i>
</div>
<button id="button" onclick="setCaret()">focus</button>
JavaScript
function setCaret() {
var el = document.getElementById("editable");
recurseDOM(el);
el.focus();
}
function recurseDOM(el) {
var nIndex = 0;
var elNode = el.childNodes[nIndex];
while(elNode) {
var tag =elNode.tagName;
if(tag) {
if(elNode.childElementCount) {
recurseDOM(elNode);
} else {
var range = document.createRange();
var sel = window.getSelection();
range.selectNode(elNode);
sel.removeAllRanges();
sel.addRange(range);
var isBold = document.queryCommandState("Bold");
var isItalic = document.queryCommandState("Italic");
var isUnderline = document.queryCommandState("Underline");
var isStrike = document.queryCommandState("StrikeThrough");
document.execCommand('removeFormat', false, null);
if(isBold) document.execCommand('bold', false, null);
if(isItalic) document.execCommand('italic', false, null);
if(isUnderline) document.execCommand('underline', false, null);
if(isStrike) document.execCommand('strikeThrough', false, null);
}
}
nIndex++;
elNode = el.childNodes[nIndex];
}
}