I've seen lots of question about caret position. Most of them are very old.
I have a div with children that has content editable set to true.
<div tabindex="-1" id="id0" contenteditable="true" >
<p class="circle"></p>
<p class="corner"></p>
text here
</div>
function getCaretPosition(element) {
let element2 = $(element).get(0);
let caretOffset = 0;
let range = window.getSelection().getRangeAt(0);
let preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element2);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
return caretOffset;
}
setInterval(function(){
console.log(getCaretPosition(document.getElementById("id0")));
},1000);
When I get the caret, it appears to be offset, depending on child elements of the div. How can this be fixed? I don't want to hard code the offset.