I'm trying to find a way with javascript to highlight the text the user selects when they click some odd highlight button (as in <span style="background-color:yellow">highlighted text</span>). It only has to work with either WebKit or Firefox, but it seems to be well nigh impossible because it has to work in the following cases:
<p>this is text</p>
<p>I eat food</p>
When the user selects from "is text" through "I eat" in the browser (can't just put a span there).
and this case:
<span><span>this is text</span>middle text<span>this is text</span></span>
When the user selects from "is text" to "this is" in the browser (even though you can wrap your highlight spans around each element in the selection, I'd like to see you try to get that middle text highlighted).
This problem doesn't seem to be solved anywhere, frankly I doubt it's possible.
It would be possible if you could get the Range that you get from the selection as a string complete with html which could be parsed and then replaced, but as far as I can tell you can't get the raw html of a Range.. pity.
This is my first time posting here, but looking through your answers, wouldn't something like this work? I have a sample here: http://henriquedonati.com/projects/Extension/extension.html
Here is a complete code to highlight and dehighlight the text
https://jsfiddle.net/Bilalchk123/1o4j0w2v/
I was having the same problem today, highlighting the selected tags ranging over multiple tags. The solution:
Refer the code below , for further clarification.
This answer is probably a few years too late for you, but I faced a similar problem and wanted to document it here, since it is the first hit on google.
To reiterate, the problem is that you would like to just capture the Range object from the User Selection and surround it with a styled div, like so:
But as Original Parent states, this is unsafe. It will work if the selection does not cross element boundaries, but it will throw a DOM eror if the Range created by the User Selection is an unsafe range which crosses the boundaries of HTML tags.
The solution is to produce an array of smaller Range objects, none of which individually crosses an element barrier, but which collectively cover the Range selected by the user. Each of these safe Ranges can be highlighted as above.
It is then possible to (appear to) highlight the User Selection, with this modified code:
Note that you'' probably need some fancier CSS to make the many disparate elements a user could look nice together. I hope that eventually this helps some other weary soul on the internet!
Well, you can do it using DOM manipulation. This works in Firefox:
Seems to work in the current version of Safari as well. See https://developer.mozilla.org/en/DOM/range.surroundContents and http://www.w3.org/TR/2000/REC-DOM-Level-2-Traversal-Range-20001113/ranges.html