
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Click on Hidden Element Using Selenium WebDriver
We can click on an element which is hidden with Selenium webdriver. The hidden elements are the ones which 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(); driver.get("https://learn.letskodeit.com/p/practice"); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // 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() } }