My current solution is:
- Get selected html (include text and html tag), namely: selText
- highlightText =
<span>selText</span>
- Find
selText
ininnerHTML
of the body or document (or the element which the mouse dragged in) - Replace with
highlightText
But if the document is: a a a a a a
and user selects the last a
. My function will highlight the first or all a
.
Any suggestion?
Thank you.
i think your question is duplicated, anyway i just searched the internet and found this article.
Below the final code to achieve what you ask
I also found this library rangy that is an helper you can use to select text but only works with jquery so i prefer the first vanilla-js solution.
On Range and User Selection
You have to select range using Document.createRange that return a Range object before you can use Range.surroundContents(), you could create a range this way.
In practice you follow this guide to understand range and selection tecniques. The most important point is contained in this code
After this you can use