How to interact with hidden elements in Selenium Webdriver?

We can interact with hidden elements in Selenium Webdriver. The hidden elements are the ones that are present in the DOM but not visible on the page. Mostly the hidden elements are defined by the CSS property style="display:none;". In case an element is a part of the form tag, it can be hidden by setting the attribute type to the value hidden.

Selenium by default cannot handle hidden elements and throws ElementNotVisibleException while working with them. Javascript Executor is used to handle hidden elements on the page. Selenium runs the Javascript commands with the executeScript method. The commands to be run are passed as arguments to the method.

First of all, the getElementById method can be used to identify the element. Next to enter text to the field, the value method is used to set value to the field.



Let’s take an example where there are two buttons Hide and Show. Also there is an edit box below the buttons. Once we click on the Hide button, the edit box disappears from the page.

Now let us enter some text inside the hidden text box.


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 ElementHidden{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();

      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      //URL launch

      // identify element and click

      // Javascript executor class with executeScript method
      JavascriptExecutor j = (JavascriptExecutor) driver;

      // identify element and set value
      String s = (String) j.executeScript("return
      System.out.print("Value entered in hidden field: " +s);


Updated on: 22-Nov-2021

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started