Wrox Home  
Search P2P Archive for: Go

  Return to Index  

javascript thread: Problem with textRange in stylesheet-based DHTML editor


Message #1 by "Danny Manners" <dannym@n...> on Fri, 25 Jan 2002 02:59:31
I'm developing a DHTML editor for IE which I want to be stylesheet based. 
The user will be able to select block or inline styles from dropdown menus 
and apply them to selected paragraphs or text ranges respectively, which 
will end up with enclosing <P class=ablockstyle></P> or <SPAN 
class=aninlinestyle></SPAN> tags.

execCommand() doesn't have the command identifiers to do this. So I wrote 
code to examine a selected textRange and insert the tags myself. In the 
simplest cases, this is easy. However, the algorithm has to handle any 
arbitrary user selection, which might span multiple or partial blocks or 
existing spans and other tags.

Having sweated over it, the code is done, but I have a horrible problem 
with the textRange. In the following example, assume that everything 
from "cats" to "dogs" inclusive has been selected for applying an inline 
style:

<p>It is a well known fact that cats hate mice.</p>
<p>However, <i>dogs are indifferent to them.</i></p>

My code will produce this:

<p>It is a well known fact that <span class=something>cats hate 
mice.</span></p>
<p><span class=something>However, </span><i><span class=something>dogs 
</span>are indifferent to them.</i></p>

It's clever enough to split the span to ensure the HTML is well-nested. 
Unfortunately, I wrote it on the assumption that the value of 
textRange.htmlText would be:

cats hate mice.</p><p>However, <i>dogs

...so that I could recognise and deal with blocks/spans/tag pairs that 
overlap the beginning or end of the selection. Unfortunately, MSHTML 
automatically completes any singleton tags, and actually returns the 
following for textRange.htmlText:

<p>cats hate mice.</p><p>However, <i>dogs</i></p>

The result is that my code produces mangled HTML.

Can anyone offer any advice? There doesn't seem to be a direct way to 
inspect the HTML on either side of a textRange. I could access 
textRange.parentElement().innerHTML and then search for textRange.htmlText 
in that, but this could fail in the case where the selection is a piece of 
HTML that occurs identically more than once in a document.

MSHTML does 80% of the work needed for a simple WYSIWIG editor, but I 
can't see any way round this problem. Or is there a completely different 
approach?

Thanks in advance for any help.

Danny

  Return to Index