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