Reputation: 129
Because execCommand doesn't work as expected I want to build a similar function on my own. It should be possible to apply different styles to a text. If I want to add a style it is easy as I can simply use range.surroundContents which let me put for example a span-tag around the selection. I also can remove tags by removing parent nodes from the current cursor position. The only think I can't find a solution to is how to handle the following cases with overlapping tags:
Case A:
<span class="bold">This is some text</span> that goes on <span class="italic">and on until the end</span>
Imagine User selects the text from some to until and applies a underline. The change should be like:
<span class="bold">This is <span class="unterline">some text</span></span><span class="underline"> that goes on </span><span class="italic"><span class="underline">and on until</span> the end</span>
Case B:
<span class="bold">This is some text</span> that goes on <span class="italic">and on until the end</span>
Imagine User selects the text from some to until and applies a bold. The change should be like:
<span class="bold">This is some text that goes on </span><span class="italic"><span class="bold">and on until</span> the end</span> ... or similar valid output.
Case C:
<span class="color-orange">This is some text</span> that goes on <span class="color-blue">and on until the end</span>
Imagine User selects the text from some to until and applies a yellow color. The change should be like:
<span class="color-orange">This is </span><span class="color-yellow">some text that goes on and on until</span><span class="color-blue"> the end</span>
How can I achieve that? As it seems like a common problem I'm pretty sure that someone already figured this out but I couldn't find anything yet. Hopefully someone around SO can at least point me in the right direction. Thank you!
Upvotes: 1
Views: 443
Reputation: 324567
Short answer: it's hard to do this sensibly and reliably for the general case. I started work on a Rangy module for this, got bogged down and abandoned it.
Take a look at the draft HTML Editing specification Aryeh Gregor of Google worked on a couple of years ago. He also wrote an unoptimized JavaScript implementation of the algorithms in his spec targeted at the latest browsers of the time.
Upvotes: 2