javascripthtmlqueryselectoratag

Can't find atag link with document.querySelector


I am trying to find a link that contains: ng-click="showModal()" and has the innerText: 1122334455

I have tried to use the below code but it doesn't find the link(atag). I am not sure what could be the problem in the codeline that uses: document.querySelector? (That line is the problem)

HTML code for where the atag is located and look like:

<td class="col-reservation-id text-center">
  <span class="overflow-text">
    <a class="highlight" ng-click="showModal()">1122334455</a>
  </span>
</td>

C#/javascript code to find the above atag

public async Task<bool> clicklink(ChromiumWebBrowser browser)
{
    String atag = "document.querySelector('" + "a[ng-click=" + '"' + "showModal()" + '"' + "].innerText === '1122334455'" + "')";

    String clickinputscript = atag + ".focus(); " +
                              atag + ".click(); ";

    bool success = false;
    try
    {
        success = (await browser.GetMainFrame().EvaluateScriptAsync(clickinputscript)).Success;
    }
    catch (Exception ex) { success = false; }
    return success;
}

Solution

  • You can't place JS code inside document.querySelector's query string.

    You have to do it after selection. To do it, use document.querySelectorAll and a for loop instead:

    for(const element of document.querySelectorAll('a[ng-click="showModal()"]').values()){
      if(element.innerText === '1122334455'){
        element.focus()
        element.click()
        break
      }
    };
    

    Or, converted to C#-land:

    String clickinputscript = "for(const element of document.querySelectorAll('a[ng-click=" + '"showModal()"'+"]').values()){if(element.innerText === '1122334455'){element.focus();element.click();break;};};";