C# Remove the underline under a link when selecting more than the link

323 views Asked by At

I'm trying to remove the underline under a link when I'm selecting the link and text at the same time. I know element = element.children isn't working but I can't find a way to do it.

    private void UnderlineExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        if (htmldoc != null)
        {
            htmldoc.Underline();
            IHTMLSelectionObject selec = htmldoc.GetSelection();
            IHTMLElement element = null;
            IHTMLTxtRange txtRange = (IHTMLTxtRange)htmldoc.GetIHTMLDocument2().selection.createRange();
            element = txtRange.parentElement();


            while (element != null
                && !(element.tagName.Equals("A", StringComparison.InvariantCultureIgnoreCase)))
            {
                if (element.tagName.Equals("A"))
                {
                    element.style.setAttribute("text-decoration", "none");
                }
                element = element.children;
            }
        }
    }

Knowing that the HTML-text of the selected range is a <U> tag, and an <A> tag and another <U> tag.

Thanks for answers!

1

There are 1 answers

0
dridriun On

I found the solution it was easy. I didn't search the right way. I didn't know that we could create a IHTMLElementCollection with a IHTMLElement. Here is my code :

    private void UnderlineExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        if (htmldoc != null)
        {
            bool underline = false;
            htmldoc.Underline();
            IHTMLSelectionObject selec = htmldoc.GetSelection();
            IHTMLElement element = null;
            IHTMLTxtRange txtRange = (IHTMLTxtRange)htmldoc.GetIHTMLDocument2().selection.createRange();
            element = txtRange.parentElement();
            if (element.tagName.Equals("A"))
            {
                element.style.setAttribute("text-decoration", "none");
            }
            IHTMLElementCollection children = element.all;
            foreach (IHTMLElement child in children)
            {
                if (child.tagName.Equals("U"))
                {
                    underline = true;
                }
            }
            foreach (IHTMLElement child in children)
            {
                if (child.tagName.Equals("A") && underline == false)
                {
                    child.style.setAttribute("text-decoration", "none");
                }
            }
        }