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?
Approach: Select the HTML element which need to remove. Use JavaScript remove() and removeChild() method to remove the element from the HTML document.
Activate the "select element" feature of the browser, move the mouse over the element you want to delete, and click on it to jump to it in the source code. Step 3. Right-click on the element in the code, and select "delete element", or press the Del-key directly, to remove it from the page.
display: none; 'Unlike the visibility property, which leaves an element in normal document flow,display: none removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code. This is because it is, indeed, removed from the document flow.
webbrowser.Document.GetElementById("element").OuterHtml = "";
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);
}
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With