'On selecting text from HTML paragraph using window.getSelection(), the range index value is giving 0 when text from different/child tag is selected

I am trying select text from a HTML paragraph and get the index range.

To get the range values, i'm using the below code

{
startIndex = window.getSelection().getRangeAt(0).startOffset;
endIndex = window.getSelection().getRangeAt(0).endOffset;
}

Below is the HTML paragraph.

<p>Pellentesque <b>habitant</b> morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>

Now when i select the word "habitant" the startOffset() is returning 0 as a new/child tag started but i need the index starting from the paragraph



Solution 1:[1]

It returns 0 because the work "habitant" is wrapped inside another node so the anchor node won't be the hall paragraph it'll be just the node <b>haitant</b> you can either fix this by removing the tag <b>.

<p class="text">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>

another workaround will be to search for the selected word inside the parent node

<p class="text">Pellentesque <b>habitant</b> morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>



const getSelectedTextIndex = () => {
    const selectedText = window.getSelection().toString()
    startIndex = document.querySelector('.text').innerText.indexOf(selectedText)
    endIndex = startIndex + selectedText.length
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ahmed Selim