Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 8 down vote accepted

Along the lines of,

JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.linkText("Click ME"));
js.executeScript("arguments[0].setAttribute('attr', '10')",element);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.