javascript - Selection range to HTML element -


How can I convert a selected element to an HTML element?

For example, the string quick brown fox jumps over the lazy dog ​​, I have received the part brown which indicates the selection number Start = 10 and end = 14 (selection is not created by user input).

Now, I get this part of the string & lt; Span & gt; Brown & lt; / Span & gt; ?

PS I have seen the answer provided uses execCommand, but it does not satisfy me, because I need it to be as transparent as possible.

I am using the range API for selection, but in this case - "Selection" is only stored in the start / end location pointers Does not really have any selection.

I had an idea that I can use the indicators to make a selection in the background, and it will be invisible to the user, but then ... I do not know how to execute it.

Thanks in advance!

In this case you can do this by using the range . I'm assuming that your text is contained in the same text node, for example:

  & lt; Div id = "test" & gt; Quick brown fox jumps on lazy dogs & lt; / Div & gt;   

First, create a range:

  var range = document.createRange (); Var textNode = document.getElementById ("test"). FirstChild; Range.setStart (text node, 10); Range .setEnd (text node, 15);            Var span = document.createElement ("Span"); Range.surroundContents (period);   

However, it will not work in some more complex cases where the selection node crosses the boundaries. In addition, IE & lt; 9 does not support the range , so you will need a completely different solution for those browsers.

Live demo:

Self-promotion section

For more complex cases, you can use my library and , Which means that any arbitrary selection or range is and lt; Span & gt;

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

python - referencing a variable in another function? -