put span on selected text

203 Views Asked by At

how to make selected text stay surrounded by a span without breaking any Tag-element (javascript)

one exaple:

original text:

<p> a foo </p>
<p> another bar </p>

selected:

a foo
anoth
er bar

I do not want break the html nesting structure:

 <p> a fo<span>o </p>
<p> anoth</span>er bar </p>

I need something like this:

 <p> a fo<span>o </span></p>
 <p> <span>anoth</span>er bar </p>
3

There are 3 best solutions below

8
On

Using this excellent treeWalker implementation, here is a jsFiddle. Please let me know if this works for you. Side note, use rangy it is awesome.

EDIT: Nope, wait, fixed.

0
On

It's not possible. Imagine this:

<p> a foo </p>
<p> another bar </p>

resulting in:

a foo
another bar

Now if a user selects only a portion, lets say:

a foo
anoth
er bar

you break the html nesting structure:

 <p> a fo<span>o </p>
<p> anoth</span>er bar </p>

This is impossible to achieve with only one tag.

0
On

You're going to need to iterate through each character in the selected text, grouping the characters by the DOM node in which they reside. After you've created the groups, you'll want to wrap each group within the <span> tags.

You could do this by looking at the anchorNode and focusNode properties of the selection object, as well as testing other plausable nodes (ie. all children of the common parent/ancestor of the anchor and focus nodes) with the containsNode() method.