Search code examples
javascriptc#getelementsbyclassname

Simulate click javascript to element by class


I am using execelementasync in c#.

I want to use JavaScript too simulate a click to this button:

<a class="btn confirm" href="#">
  <h5>
    Begin
  </h5>
</a>

My code:

string jsScriptB = System.Xml.Linq.XElement.Parse(@"<js><![CDATA[ document.getElementByClassName('btn confirm').click();]]></js>").Value;
            browser.ExecuteScriptAsync(jsScriptB);

I am really not sure what is going wrong but the button does not click.

Question: How can I click that button using JavaScript


Solution

  • In Javascript document.getElementsByClassName will return a array of HtmlElement so you can't call click on it directly. you need to click on a single element

    document.getElementsByClassName('btn confirm')[0].click();

    Secondly you are trying to use 2 class in your getElementByClassName which is invalid in first place.

    You can better call it like

    document.querySelectorAll('.btn,.confirm')
    

    or just call querySelector if there is only one element in your html document. later you can call it like

    browser.Document.GetElementById(".btn,.confirm").InvokeMember("click");