0

I have referred Getting selected text position and Get selected text position and place an element next to it but it's not working in my case.

My case is I want to get the start and end position of highlighted text and my code is

// TO GET THE HIGHLIGHTED TEXT VALUE
  const handleMouseUp = () => {
    const selectedTextValue = window.getSelection().toString()
    console.log(selectedTextValue)
  }

But when I use the below code then

// TO GET THE HIGHLIGHTED TEXT VALUE
  const handleMouseUp = () => {
    const selectedTextValue = window.getSelection().toString()
const oRange = selectedTextValue.getRangeAt(0); //get the text range: ;
const oRect = oRange.getBoundingClientRect();
    console.log(oRect)
  }

I get the error Property 'getRangeAt' does not exist on type 'string'.

Where am I going wrong ? Please help !

Sachin
  • 149
  • 1
  • 16
  • ```.toString()``` converts your element to string and the error clearly states string doesn't have a function named ```getRangeAt``` i would recommend try without ```toString``` – pavan kumar Dec 27 '21 at 12:07
  • 1
    You need to call `getRangeAt()` at the result of `getSelection()`, not after converting it to a string. Docs here: https://developer.mozilla.org/en-US/docs/Web/API/Selection/getRangeAt – Peter B Dec 27 '21 at 12:07
  • But I want the highlighted text as string @pavankumar – Sachin Dec 27 '21 at 12:15
  • @PeterB do you mean like this const selectedTextValue = window.getSelection().getRangeAt(0).toString() – Sachin Dec 27 '21 at 12:18
  • You're trying to do two different things: do you want the selected text as a string, or do you want the position and bounds of the selection? – skara9 Dec 27 '21 at 12:34
  • @skara I want both highlighted text as string and then start and end position of the highlighted text – Sachin Dec 27 '21 at 12:36

0 Answers0