How to use javascript to set attribute of selected web element using selenium Webdriver using java?

前端 未结 3 787
鱼传尺愫
鱼传尺愫 2020-12-09 11:22

I want to use javascript to set attribute for selected element on webpage.

I have found 2 ways to set attribute using javascript

1

   WebDriv         


        
3条回答
  •  抹茶落季
    2020-12-09 11:45

    As per your code trials:

    driver.findElement(By.linkText("Click ME"))
    

    The innerHTML seems to be set as Click ME.

    So, to set a new value e.g. 10 as the innerHTML you can use the executeScript() method of the JavascriptExecutor interface and you can use the following solution:

    • Using innerHTML:

      WebDriver driver;
      WebElement element = driver.findElement(By.linkText("Click ME"));
      JavascriptExecutor jse = (JavascriptExecutor) driver;
      jse.executeScript("arguments[0].setAttribute('innerHTML', '10')", element);
      

    Ideally, you need to you need to induce WebDriverWait for the elementToBeClickable() and and you can use the following solution:

    • Using textContent:

      WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Click ME")))
      ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('textContent','10')", element);
      

    Reference

    You can find a relevant detailed discussion in:

    • Selenium Datepicker using JavascriptExecutor

提交回复
热议问题