I am seeking a way to utilize Javascript in order to set attributes for the selected element on a webpage.
After some research, I have discovered two methods for achieving this with Javascript:
Method 1
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementByID('//id of element').setAttribute('attr', '10')");
Method 2
WebElement element = driver.findElement(By.id("foo"));
String contents = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].innerHTML;", element);
However, my challenge lies in applying Javascript to a specific WebElement that I have located using Selenium WebDriver.
For instance, after selecting a link with Selenium WebDriver:
driver.findElement(By.linkText("Click ME"))
I now wish to set an attribute for this particular WebElement using Javascript.
I am unsure how to merge these two approaches and would greatly appreciate any guidance in finding a solution.