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
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);
You can find a relevant detailed discussion in: