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
an开发者_运维技巧d 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:
<div id="test">The quick brown fox jumps over the lazy dog</div>
First, create the range:
var range = document.createRange();
var textNode = document.getElementById("test").firstChild;
range.setStart(textNode, 10);
range.setEnd(textNode, 15);
To surround just the word "brown" within a span, you can use the range's surroundContents()
method:
var span = document.createElement("span");
range.surroundContents(span);
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.
Suppose that The quick brown fox jumps over the lazy dog
is wrapped in some element, say a DIV, for example:
<div id='myText'>The quick brown fox jumps over the lazy dog</div>
You could write something like this:
var ele = document.getElementById('mytext');
var myText = ele.innerHTML;
var start = 10;
var end = 14;
var newText = myText.substring(0, start) + '<span>' + myText.substring(start, end) + '</span>' + myText.substring(end);
ele.innerHTML = newText;
JavaScript provides a number of string manipulation methods. Try Googling JavaScript String Methods
.
精彩评论