How can I transform a selected text range into a HTML element?
For example, string The quick brown fox jumps over the lazy dog, I’ve fetched the part brown that reflects selection points start = 10 and end = 14 (selection isn’t built by user input).
Now, how do I transform this part of string into a <span>brown</span>?
P.S. I’ve looked into How to wrap with HTML tags a cross-boundary DOM selection range?. The answer provided uses execCommand, but that doesn’t satisfy me, because I need this to be as transparent as possible.
I’m using Range API for selections too, but as in this case- the “selection” is just stored pointers of start/end locations with no selection actually made.
I had an idea that I could use the pointers to create a selection in the background, wrap with </span> and that would be invisible to user, but then again… I have no idea how to execute this.
Thanks in advance!
You can do this in this case using methods of
Range. I’m assuming your text is all contained in a single text node. For example:First, create the range:
To surround just the word “brown” within a span, you can use the range’s
surroundContents()method:However, this won’t work in some more complicated cases where the selection crosses node boundaries. Also, IE < 9 does not support
Range, so you’d need a completely different solution for those browsers.Live demo: http://jsfiddle.net/m3yJ5/
Self-promotion section
For more complicated cases, you could use my Rangy library and its CSS class applier module, which surrounds any arbitrary selection or range in
<span>s with a particular CSS class.