How to create a Javascript executor for making an element visible in Selenium Webdriver?

We can create a JavaScript Executor for making an element visible in Selenium webdriver. A hidden element has a style attribute whose value set to display: none.

For making an element visible on the page we have set the value of style attribute to block/ inline/ flex/ inline-block. Let us see the html code of an element which is visible(style= display: block) −

Now on clicking the Hide button, the Hide/Show Example edit box becomes invisible on the page. Let us now see the html code of the Hide/Show Example edit box in hidden state(style= display: none) −

JavaScript Executor can make the same element visible on the page. Selenium executes JavaScript commands with the help of the executeScript method.

JavaScript command to be executed is passed as a parameter to this method.

First we shall identify the element with the help of document.getElementById method and set the style.display attribute as 'block'. This shall be passed as a parameter to executeScript method.


JavascriptExecutor j = (JavascriptExecutor)driver;


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 MakeElementVisible{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //launch URL
      WebElement l = driver.findElement("displayed-text"));
      // Javascript Executor to make hidden element visible
      JavascriptExecutor j = (JavascriptExecutor) driver;
      //verify element is visible
      boolean b = l.isDisplayed();
         System.out.println("Element is visible");
         System.out.println("Element is not visible");


Updated on: 07-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started