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

前端 未结 3 777
鱼传尺愫
鱼传尺愫 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:22

    I have also faced a similar issue and I have used the javascript Executor

    so in my case, I have a list of elements on which I have to change one property

    here first I am finding the element, then traversing through the list, and creating a javascriptExecutor object and then executing the script on that particular element

    //arguments[0] means the element
    //arguments[1] means the property
    //arguments[2] means the new value of the propert
    
    
    List<WebElement> unselectableDiv = driver
                    .findElements(By.xpath("//div[@class='x-grid3-cell-inner x-grid3-col-6']"));
    
            for (WebElement element : unselectableDiv) {
    
                // System.out.println( "**** Checking the size of div "+unselectableDiv.size());
    
                JavascriptExecutor js = (JavascriptExecutor) driver;
    
                String scriptSetAttr = "arguments[0].setAttribute(arguments[1],arguments[2])";
    
                js.executeScript(scriptSetAttr, element, "unselectable", "off");
    
                System.out.println(" *****   check value of Div property " + element.getAttribute("unselectable"));
    
            }
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-09 11:46

    Along the lines of:

    JavascriptExecutor js = (JavascriptExecutor) driver;
    WebElement element = driver.findElement(By.linkText("Click ME"));
    js.executeScript("arguments[0].setAttribute('attr', '10')",element);
    
    0 讨论(0)
提交回复
热议问题