I want to use javascript to set attribute for selected element on webpage.
I have found 2 ways to set attribute using javascript
1
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementByID('//id of element').setAttribute('attr', '10')");
2
WebElement element = driver.findElement(By.id("foo"));
String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element);
But I want to apply javascript to specific webelement which i have found using selenium webdriver
as an example i have select one link using selenium webdriver
driver.findElement(By.linkText("Click ME"))
Now I want to set attribute of this webelement using javascript
but I don't know how to combine both
please help me to find solution
To set the attribute we shall use the setAttribute method. JavascriptExecutor j = (JavascriptExecutor) driver; js. executeScript ("document. getElementsByClassName('heading')[0].
Selenium WebDriver with JavaScript is a favorable combination to perform automated UI testing of applications. JavaScript offers efficiency with its well-built and structured patterns and functions, making the script more compact. It offers security and is well supported by a large community of developers.
To simplify the usage of JavascriptExecutor in Selenium, think of it as a medium that enables the WebDriver to interact with HTML elements within the browser. JavaScript is a programming language that interacts with HTML in a browser, and to use this function in Selenium, JavascriptExecutor is required.
Along the lines of:
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.linkText("Click ME"));
js.executeScript("arguments[0].setAttribute('attr', '10')",element);
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"));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With