I have a website where all of the buttons have the same class name and the only differentiating part of the button is the "data-dojo-attach-point".
I am trying to click that button or select that field and input values.
<div class="btn btn-default" type="button" data-dojo-attach-point="searchAddress">Search</div>
<div class="btn btn-default" type="button" data-dojo-attach-point="buildToAddress">Build to Address</div>
i.e. like this
Set element = .document.getElementsByClassName("btn btn-default")
element.Item(0).Click
Does anyone know how I can select the correct button to click?
Thanks in advance!
You may use CSS selectors like in the below example with .querySelector()
:
Sub Test()
Dim objNode As Object
With CreateObject("InternetExplorer.Application")
.Navigate "file://C:\tmp.htm"
.Visible = True
Do While .Busy Or Not .readyState = 4: DoEvents: Loop ' wait IE
Do Until .document.readyState = "complete": DoEvents: Loop ' wait document
Set objNode = .document.querySelector("div[data-dojo-attach-point='buildToAddress']")
Debug.Print objNode.innerText ' "Build to Address"
objNode.Click
.Quit
End With
End Sub
I saved C:\tmp.htm
for testing with the following content:
<html>
<title>test</title>
<body>
<div class="btn btn-default" type="button" data-dojo-attach-point="searchAddress">Search</div>
<div class="btn btn-default" type="button" data-dojo-attach-point="buildToAddress">Build to Address</div>
</body>
</html>
Here is one more example, uses .getElementsByClassName()
and .getAttribute()
:
Sub Test()
Dim colNodes As Object
Dim objNode As Object
Dim strTarget As String
strTarget = "buildToAddress"
With CreateObject("InternetExplorer.Application")
.Navigate "file://C:\tmp.htm"
.Visible = True
Do While .Busy Or Not .readyState = 4: DoEvents: Loop ' wait IE
Do Until .document.readyState = "complete": DoEvents: Loop ' wait document
Set colNodes = .document.getElementsByClassName("btn btn-default")
For Each objNode In colNodes
If objNode.getAttribute("data-dojo-attach-point") = strTarget Then Exit For
Next
If Not objNode Is Nothing Then
Debug.Print objNode.innerText ' "Build to Address"
objNode.Click
End If
.Quit
End With
End Sub
As you can see in Immediate window objNode.innerText
is "Build to Address" that corresponds to target node having data-dojo-attach-point="buildToAddress"
.