8

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
  • 7,430
  • 9
  • 60
  • 105
Thomas
  • 32,301
  • 119
  • 343
  • 612

4 Answers4

10
webbrowser.Document.GetElementById("element").OuterHtml = "";
Tasos K.
  • 7,831
  • 7
  • 41
  • 61
  • 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 Pandrea 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
  • 16,784
  • 8
  • 51
  • 74
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
  • 20,627
  • 30
  • 92
  • 137
Pon Saravanan
  • 495
  • 4
  • 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
Hosein
  • 7
  • 4