Search code examples
javascriptselenium-webdriverxpathselenium-chromedriverwebdriver

How to click on the checkbox using Selenium Javascript and Xpath?


I am trying to target the checkbox to agree to the terms and conditions but have no name or id to use to target. I have innerHTML and innerText that I am trying to target with selenium but am only encountering errors. I am using Javascript and testing on chrome.

Code trial:

await driver.findElement(By.xpath("//*innerText[text()=’I am at least 18 years of age and agree to the Official Rules.’]")).click();

Error:

let err = new ctor(data.message)
              ^

InvalidSelectorError: invalid selector: Unable to locate an element with the xpath expression //innerText[text()=’I am at least 18 years of age and agree to the Official 
Rules.’] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//innerText[text()=’I am at least 18 years of age and agree to the Official Rules.’]' is not a valid 
XPath expression.

Image of the checkbox:

imageofcheckbox

Properties of the checkbox:

propertiesofcheckbox


Solution

  • The desired tag is a <label> tag.


    Solution

    To click on the associated with the text "I am at least 18 years of age and agree to the Official Rules" you can use the following locator strategy:

    await driver.findElement(By.xpath("//label[@for='opt_rules']")).click();