9

I use a web browser control and the document is loaded with an HTML page. I want to remove an element programmatically form the document.

Can any one guide me how can I remove any element by ID or name attribute?

Ahmad
  • 8,811
  • 11
  • 76
  • 141
Thomas
  • 33,544
  • 126
  • 357
  • 626

4 Answers4

11
webbrowser.Document.GetElementById("element").OuterHtml = "";
Tasos K.
  • 7,979
  • 7
  • 39
  • 63
  • Yes, this works, is simpler than Hanlet's solution and also has the advantage of not having to use `dynamic`. – JonP Sep 30 '16 at 12:27
  • not all elements can be removed by setting OuterHTML. When trying to do that for a `TBODY` tag for example, you get `System.NotSupportedException: 'Property is not supported on this type of HtmlElement.'` probably because you cannot remove tags that are a structural part of an HTML element. In this case you have to go up and remove the parent. – Alex P. Mar 24 '20 at 17:16
9

You can accomplish this using the Microsoft.mshtml library. I accomplished it using the power of the dynamic datatype:

private void Form1_Load(object sender, EventArgs e)
{
    webBrowser1.Navigate("https://www.google.com/");
}

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    if (e.Url.ToString() == "https://www.google.com/")
    {
        dynamic htmldoc = webBrowser1.Document.DomDocument as dynamic;
        dynamic node = htmldoc.getElementById("lga") as dynamic;
        node.parentNode.removeChild(node);
    }
}
Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
3

It is the VB.Net version. I tried removing MsHTML. but referencing that library has its own problem. The below is not a direct answer but can be workaround to stop loading external resources using iframes.

 For Each FrameElement As HtmlElement In WebBrowser1.Document.GetElementsByTagName("iframe")
 Debug.Print(FrameElement.OuterHtml)
 FrameElement.OuterHtml = Nothing
 Next
4b0
  • 21,981
  • 30
  • 95
  • 142
Pon Saravanan
  • 525
  • 5
  • 12
1

OuterHtml Can not be modified!

This code removes Css Links from WebPage:

 Sub RemoveStylesheet()
        Dim styles As HTMLStyleSheetsCollection = WB.Document.DomDocument.styleSheets
1:
        If styles.length > 0 Then
            For Each stl As Object In WB.Document.DomDocument.styleSheets
                '     stl.removeImport(0)
                If stl Is Nothing Then Continue For
                Dim st As IHTMLElement = stl.owningElement
                '  st.href = ""
                '   MsgBox(st.tagName)
                st.parentElement.removeChild(st)
            Next
            GoTo 1
        End If

     
    End Sub