1

How to get position from selected text in HTML?

the HTML content is rendered by setting innerHTML. For example 1.   2 is rendered 1. 2

The use is then selecting 2 with text selector.

const start = document.getSelection().anchorOffset

is working fine to get me the position in rendered text. Which is 5 is this case.

But is there some to get the position from HTML content (I think in this case it will be 20)

By the way great article to learn selection

Juri
  • 1,531
  • 2
  • 20
  • 43

1 Answers1

0

No, that is not possible. The problem is that the DOM doesn't know about entities. It doesn't know whether the HTML source originally contained the entity or the literal Unicode character.

However you probably don't need it. You shouldn't be working with the HTML source at this point, but with the content of the DOM. You'll need to show much more code and describe the much bigger picture.

RoToRa
  • 37,635
  • 12
  • 69
  • 105
  • i would like to perform split operation on an API. The call is expecting an array of strings, but with HTML like it was before. This is the reason why i need this. – Juri Feb 18 '22 at 12:23
  • That is still not enough information. Why can't you take the text from the DOM instead of the original HTML? – RoToRa Feb 18 '22 at 19:14
  • backend api is expecting splitted HTML. If source HTML is '   hello world' and i would like to split 'world' the api is expecting two stings '   hello ' and 'world' – Juri Feb 21 '22 at 09:27
  • You would need match the original string to the DOM string. – RoToRa Feb 21 '22 at 12:05
  • this this exactly what is needed, do you have some ideas how this can be done? appreciated – Juri Feb 21 '22 at 13:51