Implementing an extension for the WebElement object to set the element attribute values

Setting an element's attribute can be useful in various situations where the test needs to manipulate properties of an element. For example, for a masked textbox, the sendKeys() method may not work well, and setting the value of the textbox will help to overcome these issues. The WebElement interface does not have a direct method that supports setting all types of attributes.

In this recipe, we will create an extension for the WebElement and provide a method to set the attribute value of an element at runtime.

Getting ready

Create a new Java class file for the WebElementExtender.java class. We will use this class to host all the extension methods for elements.

How to do it...

Add the setAttribute() method to the WebElementExtender class, as follows:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.WrapsDriver;

public class WebElementExtender {
    public static void setAttribute(WebElement element, String attributeName, String value)
    {
        WrapsDriver wrappedElement = (WrapsDriver) element;

        JavascriptExecutor driver = (JavascriptExecutor) wrappedElement.getWrappedDriver();
        driver.executeScript("arguments[0].setAttribute(arguments[1], arguments[2])", element, attributeName, value);
    }

}

How it works...

In the setAttribute() method, we created an object of JavaScriptExecutor and retrieved WrappedDriver of the WebElement object on which we wanted to call the setAttribute() method.

Using JavaScriptExecutor, we called the JavaScript setAttribute() method to set the attribute value of an element. In this example, the contents of an input element are cleared before calling the SendKeys() method. This can also be done by calling the clear() method of the WebElement class:

WebElement email = driver.findElement(By.id("email"));
WebElementExtender.setAttribute(userName, "value", "");
userName.sendKeys("[email protected]");

See also

  • The Implementing an extension for the WebElement object to highlight elements recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.165.70