简体   繁体   中英

object becomes null after assigning it's innerhtml property

I am trying to replace some code inside an html element. At one point, I add a elements around pieces of text within a webpage. At other I need to remove it (it's a simple search engine in geckofx-based browser)

if (element.OuterHtml.Contains(spanStyle))
    if (element.Parent != null)
    {
         string oldHtml = element.OuterHtml;
         string newHtml = oldHtml.Replace(spanStyle, "").Replace("</span>", "");
         element.Parent.InnerHtml = newHtml;
    }

The problem is that I cannot replace OuterHtml of the element - instead, I am trying to replace InnerHtml of it's parent.

However, the element.Parent becomes null as soon as element.Parent.InnerHtml = newHtml; is executed, and the OuterHtml of the element still contains the span element. I have even tried replacing the text content of the element.Parent.InnerHtml to see if the problem is in removing tags, but apparently it does not make a difference - as soon as I assign the element.Parent.InnerHtml , element.Parent becomes null.

Cheers!

Bartosz

If you change the InnerHtml of the elements parent it is obvious that the child element is not longer the child of the parent and therefore element.Parent becomes null . Have you tried to store element.Parent in a temporary variable like this?

var parent = element.Parent;
...
element.Parent.InnerHtml = newHtml;
...
// do something with the variable parent here which should not be null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM