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");
iterateDOM(el);
el.focus();
}
function getTextNodesIn(node) {
var textNodes = [];
if (node.nodeType == 3) {
textNodes.push(node);
} else {
var children = node.childNodes;
for (var i = 0, len = children.length; i < len; ++i) {
textNodes.push.apply(textNodes, getTextNodesIn(children[i]));
}
}
return textNodes;
}
function iterateDOM(el) {
var elNodes = getTextNodesIn(el);
var elNode;
for (var i = 0; elNode = elNodes.pop(); i++) {
console.log(i+':'+elNode.textContent);
var range = document.createRange();
range.selectNodeContents(elNode);
var sel = window.getSelection();
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");
//now apply the formatting
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);
}
}
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);
...