3
votes

Let's assume that I have the following text within a single <p>... </p>

When a user selects a couple of words within the text, lets assume the first Quisque vestibulum is selected, I get the selected text with window.getSelection().toString(); then I apply some CSS tricks, lets say I underline the text.

When the user comes back one month later, I would like to underline same text again. How can I get an exact reference for the selected text for future reference? I don't want to highlight the second Quisque vestibulum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at dolor sit amet augue tempor venenatis vitae et nibh. Donec dignissim fringilla fermentum. In facilisis consectetur risus. Nam vel mauris magna, a feugiat nisl. Quisque vestibulum, neque eu tristique tristique, tortor mauris ornare magna, at ultricies augue orci sed enim. Nulla magna ligula, dapibus vel commodo ac, sodales ut sem. Duis lorem massa, consectetur sed molestie eget, posuere eu magna. Pellentesque sollicitudin mattis facilisis. Nunc pulvinar metus et diam dignissim sit amet pellentesque metus pretium. Quisque vestibulum, maecenas vel leo sit amet diam iaculis sollicitudin.

1
You need cookies to start withotinanai
Can the text change over time ?Gaʀʀʏ
@Garreh Yes, it is likely.noway
I don't think there is a way to get the "reference" of text. Text is not object or element. It's just a combination of some characters... The only way I know to locate a piece of text is by the offset to the start position. So you may need to implement your own logic to locate the text you want.Grant Zhu

1 Answers

1
votes

You could use the search() or indexOf() and store the position of the string as well as the actual selected text.