How to interact with hidden elements in Selenium Webdriver?

Rest AssuredSelenium Web DriverDynamic Programming

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.

Syntax

executor.executeScript
("document.getElementById('txt').value='Selenium'");

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.

Example

Code Implementation.

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 ElementHidden{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();

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

      //URL launch
      driver.get("https://learn.letskodeit.com/p/practice");

      // identify element and click
      driver.findElement(By.id("hide-textbox")).click();

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

      // identify element and set value
      j.executeScript
      ("document.getElementById('displayed-text').value='Selenium';");
      String s = (String) j.executeScript("return
      document.getElementById('displayed-text').value");
      System.out.print("Value entered in hidden field: " +s);
      driver.close()
   }
}

Output

raja
Updated on 22-Nov-2021 11:19:22

Advertisements