Vijay Penny
Vijay Penny

Reputation: 41

getelement by class name for clicking

I am creating a windows form in VB.NET with web browser control, but not able to click on the below code.

<input type="Submit" class="btn btnSearch bold include_WidthButton" value="Search">

I can click when it is get element by ID, but not by classname. Please help me so much of googling didn't help me.

This is what I tried:

For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("btn btnSearch bold include_WidthButton")
    If Element.OuterHtml.Contains("btn btnSearch bold include_WidthButton") Then
        Element.InvokeMember("click")
    End If
Exit For

Upvotes: 3

Views: 6183

Answers (2)

Dũng IT
Dũng IT

Reputation: 2999

This is my solution:

Public Sub clickButton(ByVal web As WebBrowser, ByVal tagname As String, ByVal attr As String, ByVal contains As String, ByVal sleep As Integer)
    Try
        If (web.Document IsNot Nothing) Then
            With web.Document
                For Each Elem As HtmlElement In .GetElementsByTagName(tagname)
                    If (Elem.GetAttribute(attr).Contains(contains)) Then

                        Elem.InvokeMember("Click")
                        Thread.Sleep(sleep)
                        Return
                    End If
                Next
            End With
        End If
    Catch ex As Exception
        Show_Error(MODULE_NAME, "clickButton")
    End Try
End Sub

use:

clickButton(WebBrowser1, "button", "classname", "btn btnSearch bold include_WidthButton", 2000)

Upvotes: 0

Sean Wessell
Sean Wessell

Reputation: 3510

There is no native function to get a collection of elements by class using the webbrowser document. However you can create your own collection using a function and looping through all elements using the document.all property.

Function ElementsByClass(document As HtmlDocument, classname As String)
    Dim coll As New Collection
    For Each elem As HtmlElement In document.All
        If elem.GetAttribute("className").ToLower.Split(" ").Contains(classname.ToLower) Then
            coll.Add(elem)
        End If
    Next
    Return coll
End Function

Use would be like this:

Private Sub UpdatBtn_Click(sender As System.Object, e As System.EventArgs) Handles UpdatBtn.Click

    For Each elem As HtmlElement In ElementsByClass(WebBrowser1.Document, "form")
        elem.SetAttribute("className", elem.GetAttribute("className") & " form-control")
    Next

End Sub

I see you are trying to base your collection off the entire className instead of an individual class so you would need to slightly modify.

Upvotes: 1

Related Questions