Search code examples
javascriptdomselectionoffset

Is there a non-naïve way of calculating a logical offset from a DOM offset?


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:

  • A reference to the parent element
    This element contains nothing but inline elements (specifically, <span>s) and text nodes, but they are arbitrarily nested.
  • Selection.anchorNode / Selection.focusNode
    This is a reference to the text node that contains the fragment of text containing the offset position.
  • Selection.anchorOffset / Selection.focusOffset
    This is a non-negative integer, where 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?


Solution

  • 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.