[testing] Selenium: Can I set any of the attribute value of a WebElement in Selenium?

I have a WebElement, I want to reset its an attribute's value to some other value (for e.g. attr is the attribute, and I want to change its original value=1 to new value=10).

Is it possible? I am using Selenium 2.0 (WebDriver.)

This question is related to testing selenium

The answer is


I have created this jquery that solved my problem.

public void ChangeClassIntoSelected(String name,String div) {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
                "   $(element).addClass('ui-selected');\n" +
                "});");
    }

With this script you are able to change the actual class name into some other thing.


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");

I have posted a similar solution for the same problem,

visit How to use javascript to set attribute of selected web element using selenium Webdriver using java?

Here First we have find the element in my case I have found the element using xpath then we have traverse through the list of elements and then We have cast the driver object to the Executor object and create a script here the first argument is the element and second argument is the property and the third argument is the new value

List<WebElement> unselectableDiv = driver
                .findElements(By.xpath("//div[@class='x-grid3-cell-inner x-grid3-col-6']"));

        for (WebElement element : unselectableDiv) {

            // System.out.println( "**** Checking the size of div "+unselectableDiv.size());

            JavascriptExecutor js = (JavascriptExecutor) driver;

            String scriptSetAttr = "arguments[0].setAttribute(arguments[1],arguments[2])";

            js.executeScript(scriptSetAttr, element, "unselectable", "off");

            System.out.println(" *****   check value of Div property " + element.getAttribute("unselectable"));

        }

    JavascriptExecutor js = (JavascriptExecutor) driver;        
    js.executeScript("document.getElementsByClassName('featured-heading')[0].setAttribute('style', 'background-color: green')");

I could add an attribute using the above code in java


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);
    }
}

Another to answer this question available here answered by @nilesh https://stackoverflow.com/a/19934852/2079692

public void setAttributeValue(WebElement elem, String value){
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",
        elem, "value", value
    );
}

this takes advantage of selenium findElementBy function where xpath can be used also.


Examples related to testing

Test process.env with Jest How to configure "Shorten command line" method for whole project in IntelliJ Jest spyOn function called Simulate a button click in Jest Mockito - NullpointerException when stubbing Method toBe(true) vs toBeTruthy() vs toBeTrue() How-to turn off all SSL checks for postman for a specific site What is the difference between smoke testing and sanity testing? ReferenceError: describe is not defined NodeJs How to properly assert that an exception gets raised in pytest?

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?