How to delete div by class name using Webbrowser?

Asked

Viewed 466 times

1

Considering this code:

<div class="panel panel-default">
  <div class="panel-heading">
    <p>Informações Adicionais</p>
  </div>
  <div class="panel-body">

    <ul class="list-unstyled">
      <li>
        <strong>Data: </strong> 01/01/2016 21:05 à 02/02/2016 23:59
      </li>
      <li>
        <strong>Situação:</strong>  <span class="js-bootstrap-tooltip" title=""></span>
      </li>
      <li>
        <strong>Nota: </strong>  <span style="color: #"></span>
      </li>

      <li>
        <strong>Correção: </strong> 01/01/2016 21:05 à 02/02/2016 23:59</div>
      </li>
  </ul>
  <hr />
  <h5>Arquivos</h5>
  <hr />
  <p class="mb-10 alert alert-danger">Mensagem .....</p>

</div>
<footer id="footer" class="page-footer">
  <h6 class="pull-left no-margin">EMPRESA 1.0.0</h6>
  <h6 class="copyright pull-right no-margin">&copy; 2016 TESTE</h6>
  <a href="#acessibilidade" class="screen-reader">Retornar ao topo</a>
</footer>

Above we have the source code of the site that runs within the WebBrowser. We have two parts, the second part I can remove with the following code:

HTMLDocumentClass htmldoc=web_Pagina.Document.DomDocument as HTMLDocumentClass;
IHTMLDOMNode node=htmldoc.getElementById("footer") as IHTMLDOMNode;
node.parentNode.removeChild(node);

But how can I remove what exists inside the div with the class panel panel-default?

  • You managed to solve the problem?

2 answers

2

You want to get an element by the class attribute, right?

You need to create a method that does this for you. Just iterate all the elements of the html document by checking your classname attribute and compare it to what you’re looking for.

static IEnumerable<HtmlElement> GetElementByClass(HtmlDocument documento, string classe)
{
    foreach (HtmlElement elemento in documento.All)
        if (elemento.GetAttribute("className") == classe)
            yield return elemento;
}

With the above method just use it to find the desired node and delete it equal to the node with id footer:

HTMLDocumentClass htmldoc = web_Pagina.Document.DomDocument as HTMLDocumentClass;
IHTMLDOMNode node = GetElementByClass(htmldoc, "panel panel-default")[0] as IHTMLDOMNode;
node.parentNode.removeChild(node);
  • Good tip, but the author of the question was clear that he wants to "delete" the element and not just get, I recommend editing the answer

  • 1

    Well noted @Guilhermenascimento, edited response.

1

For the above code to be complete and correct, it is necessary to convert the first element (htmldoc) that is being passed by parameter of "HTML Document Class" for "HTML Document".

Argument 1: cannot convert from 'mshtml.HTMLDocumentClass' to 'System.Windows.Forms.HtmlDocument'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.