开发者

Selection range to HTML element

开发者 https://www.devze.com 2023-04-02 05:58 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号