4

In this question both answers used setAttribute() as WebElement functionality. However, I couldn't find this method in the Java, C# nor Python documentation, only getAttribute(). Trying to call this method from WebElement object in C# (Visual Studio) and Java (Eclipse) with the latest Selenium version produced the same results.

So my question is, does this method really exist?

Community
  • 1
  • 1
Guy
  • 46,488
  • 10
  • 44
  • 88

2 Answers2

10

After inspecting the selenium Python API docs and the source code, I can conclude - there is no such a method. And, there is nothing about it inside the WebDriver specification itself.

To set an attribute, usually a script is executed:

elm = driver.find_element_by_id("myid")
driver.execute_script("arguments[0].setAttribute(arguments[1], arguments[2]);", 
                      elm,  
                      "attr_name",
                      "attr_value")
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
6

They are using the JavascriptExecutor class.

I.e.

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");

Or an Extension Method

public static void setAttribute(this IWebElement element, string value, bool clearFirst)
{
    if (clearFirst) element.Clear();
    element.SendKeys(value);
}
  • 1
    No they are not, they are using this `driver.findElement(By.xpath("//input[@id="invoice_supplier_id"])).setAttribute("value", "your value")` – Guy Feb 01 '16 at 17:40
  • Nothing I could find. – Guy Feb 01 '16 at 17:48
  • I mean you could easily create an extension method that executes the javascript via the xpath or Id or sendkeys to the element. Look at what I editted with. – AlexCharizamhard Feb 01 '16 at 17:49
  • Yes, you could easily create this method. However, they didn't show JavaScript implementation, they used it as `WebElement` method. They chained this method to `driver.findElement()`, which return `WebElement`. – Guy Feb 01 '16 at 17:53
  • Which is why I am led to believe that it is similar to the extension method I posted. – AlexCharizamhard Feb 01 '16 at 17:53
  • If you really want to be able to set the properties of your htmlcontrols .NET's CodedUI Framework allows you to access them and change them. – AlexCharizamhard Feb 01 '16 at 17:54
  • 1
    I will look into it. But they didn't mention any changes in the html controls, they simply called the method as it was part of `WebElement` API. – Guy Feb 01 '16 at 17:59