Suppose I have this HTML element:
Hello everyone! This is my home page
Bye!
>
This solution works by counting length of text content of previous siblings walking back up to the parent container. It probably doesn't cover all edge cases, although it does handle nested tags of any depth, but it's a good, simple place to start from if you have a similar need.
calculateTotalOffset(node, offset) {
let total = offset
let curNode = node
while (curNode.id != 'parent') {
if(curNode.previousSibling) {
total += curNode.previousSibling.textContent.length
curNode = curNode.previousSibling
} else {
curNode = curNode.parentElement
}
}
return total
}
// after selection
let start = calculateTotalOffset(range.startContainer, range.startOffset)
let end = calculateTotalOffset(range.endContainer, range.endOffset)