1

HTML

<a onclick="loadYearPage('2018-2019')" style="cursor: pointer;">2018-2019</a>

How to target element onclick using CSS selector

i have tried below codes but not working

ie.document.querySelector("[onclick='loadYearPage('2018-2019')']").Click

Kindly suggest

QHarr
  • 83,427
  • 12
  • 54
  • 101
Ashish
  • 83
  • 5

2 Answers2

2

Tim's answer would be my preference as it escapes nicely. You can also specify multiple css attribute = value selectors with different operators and combine as And syntax

ie.document.querySelector("a[onclick^=loadYearPage][onclick*='2018-2019']")

If either of those substrings only appears once on the page you may be able to reduce this e.g.

ie.document.querySelector("a[onclick*='2018-2019']")

Using your provided page you can indeed use the contains modifier (*) to search by partial string in the value of the onclick attribute. Below is an example where you can pass the year as a variable. I have gone for a shorter selector for greater speed. A slight wait for the element to be present is required. I have used a timed loop.

Option Explicit  
'https://www.nseindia.com/products/content/derivatives/currency/cd_historical_businessGrowth.htm
Public Sub PerformClick()
    Dim ie As InternetExplorer, t As Date, ele As Object
    Const MAX_WAIT_SEC As Long = 10
    Set ie = New InternetExplorer
    Dim yearSelection As String
    yearSelection = "2018-2019"
    With ie
        .Visible = True
        .Navigate2 "https://www.nseindia.com/products/content/derivatives/currency/cd_historical_businessGrowth.htm"

        While .Busy Or .readyState < 4: DoEvents: Wend
        t = Timer
        Do
            On Error Resume Next
            Set ele = .document.querySelector("[onclick*='" & yearSelection & "']")
            On Error GoTo 0
            If Timer - t > MAX_WAIT_SEC Then Exit Do
        Loop While ele Is Nothing
        If Not ele Is Nothing Then
            ele.Click
            While .Busy Or .readyState < 4: DoEvents: Wend
        End If
        'other code
        Stop                                     '<==Delete me later
        .Quit
    End With
End Sub
QHarr
  • 83,427
  • 12
  • 54
  • 101
1

This works:

 document.querySelector('a[onclick="loadYearPage(\'2018-2019\')"]')
Tim Williams
  • 154,628
  • 8
  • 97
  • 125