Selenium: Can I set any of the attribute value of a WebElement in Selenium?
If you're using the PageFactory pattern or already have a reference to your WebElement, then you probably want to set the attribute, using your existing reference to the WebElement. (Rather than doing a document.getElementById(...)
in your javascript)
The following sample allows you to set the attribute, using your existing WebElement reference.
Code Snippet
import org.openqa.selenium.WebElement;import org.openqa.selenium.remote.RemoteWebDriver;import org.openqa.selenium.support.FindBy;public class QuickTest { RemoteWebDriver driver; @FindBy(id = "foo") private WebElement username; public void exampleUsage(RemoteWebDriver driver) { setAttribute(username, "attr", "10"); setAttribute(username, "value", "bar"); } public void setAttribute(WebElement element, String attName, String attValue) { driver.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, attName, attValue); }}
Fancy C# extension method based on previous answers:
public static IWebElement SetAttribute(this IWebElement element, string name, string value){ var driver = ((IWrapsDriver)element).WrappedDriver; var jsExecutor = (IJavaScriptExecutor)driver; jsExecutor.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, name, value); return element;}
Usage:
driver.FindElement(By.Id("some_option")).SetAttribute("selected", "selected");