Is it possible to manually set the attribute value of a Web Element using Selenium?


Yes it is possible to manually set the attribute value of a web element in Selenium webdriver using the JavaScript Executor. Selenium can run JavaScript commands with the help of the executeScript method.

First, we shall identify the element on which we want to manually set the attribute value with the JavaScript command document.getElementsByClassname. Next to set the attribute we have to use the setAttribute method.

Let us modify the background color of the button CHECK IT NOW to yellow. By default it is green on the page.

The can be done by setting the style attribute of the background-color to yellow.

Syntax

JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeScript ("document.getElementsByClassName('mui-btn')[0].setAttribute('style', " + "'background-color: yellow')");

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class BackGroundColr{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // Javascript executor to modify background color
      JavascriptExecutor j = (JavascriptExecutor) driver;
      j.executeScript ("document.getElementsByClassName('mui-btn')[0].setAttribute('style', "
         + "'background-color: yellow')");
   }
}

Output

Updated on: 06-Apr-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements