Skip to content
Advertisement

Find range of selected text wrt parent node

I want to find the range of the selected text with respect to the parent element. So in this <p> element, the anchorOffset & focusOffset for “fox” is [16,19]

JavaScript

But if we add a <b> tag before “fox” then the values change to [1,4].

JavaScript

My best guess is, the index count starts from the end of </b> tag. But I want it to still show the original value, irrespective of the HTML within <p>. For this, I tried creating a Range, but still couldn’t figure it out. Following is the code, as a function.

JavaScript

Advertisement

Answer

Below is a modified version of your code that does what you want.

It takes both the anchor and extent nodes which are children of <p> from the selection variable (i.e. window.getSelection()).

These two nodes are passed to the calculateOffset function. For each of the nodes, the sum of the text length of the preceding siblings is calculated. Incrementing this total text length with the selection’s relative offset (the one in the child node) will yield the start and end offsets with respect to the <p> text length.

JavaScript
Advertisement