Home > Mobile >  How to find the below onclick="javascript" element using Selenium
How to find the below onclick="javascript" element using Selenium

Time:08-24

How to write a CSS for the below in selenium:

<input type="button" value="Clear Fields" onclick="javascript:clearForms()" xpath="1">

Code trials:

(By.cssSelector("input[value='Clear Fields']")).click();

But I'm getting null point exception.

CodePudding user response:

Given the HTML:

<input type="button" value="Clear Fields" onclick="javascript:clearForms()">

To click on the element you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[value='Clear Fields'][onclick*='clearForms']"))).click();
    
  • Using XPATH:

    new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@value='Clear Fields' and contains(@onclick, 'clearForms')]"))).click();
    
  • Related