πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 70 of 100
JavaScript Executor
Intermediate

Retrieving the Value of Hidden Input Fields

πŸ•΅οΈScenario Overview

Retrieving the Value of Hidden Input Fields

Key Takeaways & Cheat Sheet

  • βœ“Acknowledge Selenium’s element.getText() returns empty for hidden inputs
  • βœ“Use element.getAttribute("value") to fetch input field strings
  • βœ“Execute JavaScript return value scripts to read hidden variables
  • βœ“Verify security tokens or transactional states safely

Short Direct Answer

Selenium's `getText()` method only returns visible, rendered text. To read values from input fields or hidden variables (like CSRF tokens or user IDs), use `element.getAttribute("value")` or execute a JavaScript script that queries and returns the element's value property directly.

⚠️ Senior Warning (Red Flag)

Do not use getText() on input tags or hidden elements. getText() only extracts visible text inside node tags, returning an empty string for inputs or hidden elements.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Using getAttribute("value") is the standard approach. Use JavaScript Executor as a reliable fallback when targeting elements with customized angular bindings or hidden metadata.

SeleniumAutomation.java
Selenium 4 + Java
// βœ… Strategy 1: Read value attribute directly
WebElement tokenInput = driver.findElement(By.name("csrf-token"));
String tokenVal = tokenInput.getAttribute("value");

// βœ… Strategy 2: Retrieve value via JavaScript (Highly compatible with hidden fields)
String tokenViaJS = (String) ((JavascriptExecutor) driver).executeScript(
    "return document.getElementsByName('csrf-token')[0].value;"
);

System.out.println("CSRF Token resolved: " + tokenViaJS);