2

I would like to apply a style, such as a yellow background, to the text that a user selects on my webpage. Unfortunately, the selected text may cross node boundaries (e.g. it may begin in the middle of one div and end in the middle of another div).

What is the best way to wrap a span (or multiple spans) around all of the selected text?

Set up

<div>This sentence is not selected. THIS SENTENCE </div>
<div>IS SELECTED. This sentence is not selected.</div>

Desired result

<div>This sentence is not selected. <span>THIS SENTENCE</span> </div>
<div> <span>IS SELECTED.</span> This sentence is not selected.</div>    

Here are two similar questions (one, two) restricted to the case when the selection does not cross node boundaries.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Josh Grinberg
  • 523
  • 6
  • 14
  • Check this answer. [https://stackoverflow.com/questions/52437769/javascript-how-to-divide-selected-text-along-multiple-p-tags-into-each-content/52438315#52438315](https://stackoverflow.com/questions/52437769/javascript-how-to-divide-selected-text-along-multiple-p-tags-into-each-content/52438315#52438315) – Junsun Sep 27 '18 at 07:55

2 Answers2

0

Only Firefox allows multiple ranges per selection.
All other browsers are limited to one range with getSelection().

Esko
  • 683
  • 9
  • 23
-1

To apply a style i would suggest not missing up with your html, instead you can use this :

::selection {
    background: #ffb7b7; /* WebKit/Blink Browsers */
}
::-moz-selection {
    background: #ffb7b7; /* Gecko Browsers */
}

Anyway , the problem will be that you can only change the color and the background CSS properties.

More information about this technique can be found here : https://css-tricks.com/overriding-the-default-text-selection-color-with-css/

Abood Sy
  • 282
  • 3
  • 10