How to set style display of an html element in a selenium test?

We can set the style display of an html element with Selenium webdriver. The DOM interacts with the elements on the page with the help of Javascript. Selenium executes the Javascript commands by taking the help of the executeScript method. The commands to be executed are passed as arguments to the method.

Some operations like setting the style display be performed by Javascript Executor. The getElementById method can be used to locate the element. Then we have to apply the style.display method on the webelement and set the display type.




Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ElementStyleSet{
   public static void main(String[] args) {
      System.setProperty("", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // Javascript executor class with executeScript method
      JavascriptExecutor j = (JavascriptExecutor) driver;
      // set the display with style.display method
      j.executeScript ("document.getElementById('gsc-i-id1').style.display='block';");

Updated on: 26-Oct-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started