Martin
Martin

Reputation: 1350

put span on selected text

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>

Upvotes: 2

Views: 191

Answers (3)

user1726343
user1726343

Reputation:

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.

Upvotes: 1

JasonWyatt
JasonWyatt

Reputation: 5303

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.

Upvotes: 1

Christoph
Christoph

Reputation: 51201

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.

Upvotes: 2

Related Questions