Can I set any of the attribute value of a WebElement in Selenium?


We can set any attribute value of a webelement in Selenium. Selenium can run Javascript commands by the executeScript method. The command to be executed is passed as an argument to the method.

Next, we have to identify the element with the help of the Javascript method document.getElementsByClassname. It returns a list of elements, to point to the first element we shall add index [0]. To set the attribute we shall use the setAttribute method.

Syntax for setting the style attribute −

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

Let us set the background color of webelement to red.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class SetAttributeVal{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // Javascript executor to set background color to red
      JavascriptExecutor js = (JavascriptExecutor) driver;
      js.executeScript
      js.executeScript
      ("document.getElementsByClassName('heading')[0].setAttribute('style', 'background-color: red')");
      driver.quit();
   }
}

Output

Updated on: 30-Nov-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements