I have highlighted some of the text inside my parent element by placing it in <span>
s, and now want to work out what part of it is selected. I have retrieved the Selection
object, but it doesn't contain directly useful information. I want to get the offsets relative to the start of the text, but they're relative to the the text nodes inside the highlighting <span>
s and don't line up with parent.textContent
.
Given:
parent
element<span>
s) and text nodes, but they are arbitrarily nested.Selection.anchorNode
/ Selection.focusNode
Selection.anchorOffset
/ Selection.focusOffset
0
is before the first character.is there a way more efficient than the naïve "explore the tree with a cumulative count" technique to pretend that the <span>
s don't exist for the sake of measuring the Selection
focus and anchor points?
I don't know whether it is any more efficient in terms of performance, you would have to measure that. In terms of lines of code the Range API should make things fairly easy. Construct range from the start of the parent element to the start of the selection and then count the characters contained in it.
A Selection
is mostly a collection of ranges after all.