none
How to implement text replacement with IHTMLTxtRange properly?

    Question

  • Hi,

    I'm using an IHTMLTxtRange object instance to replace the current user's selection in the browser.

    Today, i came across the following problem. This is my markup:

    <body><p><a href="http://www.google.com">http://www.google.com</a></p></body>
    

    The user selection (html), as informed by the IHMLTxtRange instance (range), is:

    <a href="http://www.google.com">http://www.google.com</a>
    

    Whenever i execute range.replaceHTML("test"); the result is:

    <body><p><a href="http://www.google.com">test</a></p></body>
    

    This behavior seems to apply also to scenarios like this:

    <body><p><b>some text</b></p></body>
    

    Can anyone help me to develop a consistent selection replacement strategy? I mean, that text selection works as expected.

     

     

    Thanks

    Monday, May 30, 2011 7:20 PM

Answers

  • Hello,

     

    I believe the method you called to change the HTML text is pasteHTML().  If so, it is known issue but not fixed yet. The similar issue is reported to connect site at: http://connect.microsoft.com/VisualStudio/feedback/details/569921/ihtmltxtrange-pastehtml-method-does-not-replace-span-tags.

     

    There is a work around you may try. The idea is that we can get the parent element of the selection if the text we selected contains the <a>  tag, then we remove the this element directly. After that we insert the new html at this selection place using pasteHTML again. Here is the code:

     

    //doc is a IHTMLDocument2 obejct.

    IHTMLTxtRange range = doc.selection.createRange();

     

                if (range.htmlText.Contains("A href"))

                {

                    IHTMLDOMNode tempNode = range.parentElement() as IHTMLDOMNode;

                   

                    tempNode.removeNode(true);

                }

               

                range.pasteHTML("<b>some text</b>");

     

    Hope it helps.

     

    Regards,

    Yi


    Yi Feng Li [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Thursday, June 02, 2011 9:30 AM