JSFiddle - React, Tailwind, and code Playground
HTML
<div id="editor" contenteditable style="border: inset 3px;">
<p>first paragraph.</p><p><br></p>
</div>
<p id="log"></p>
<p id="selection">not focused</p>
JavaScript
var editor = document.getElementById("editor");
var log = document.getElementById("log");
var selection = document.getElementById("selection");
editor.addEventListener("focus", ()=>{ setTimeout(()=>{
var secondP = document.getElementsByTagName("p")[1];
if (secondP && secondP.firstChild) {
window.getSelection().collapse(secondP, 0);
}
}, 100)});
editor.addEventListener("input", ()=>{
log.textContent = editor.innerHTML;
});
log.textContent = editor.innerHTML;
function nodeName(aNode) {
if (aNode.tagName) {
return "<" + aNode.tagName.toLowerCase() + ">";
}
return "\"" + aNode.textContent + "\"";
}
document.addEventListener("selectionchange", ()=>{
var range = window.getSelection().getRangeAt(0);
if (range.collapsed) {
selection.textContent = "{ " + nodeName(range.startContainer) + ", " + range.startOffset + " }";
} else {
selection.textContent = "{ (" + nodeName(range.startContainer) + ", " + range.startOffset + ")-(" + nodeName(range.endContainer) + ", " + range.endOffset + ") }";
}
});