We use cookies to analyze site traffic and show personalized ads. You can accept all cookies or decline personalized advertising.
Learn more in our Privacy Policy.
Retrieve the visible text of an element as rendered on the page.
In Selenium, getText() is how you read what the user actually sees on the page.
It returns the visible inner text of an element (and its children), after the browser applies styles like display: none or visibility: hidden.
<tag>text here</tag>display: none)Use getText() when:
getText() over getAttribute("innerText") for user-facing text.<input /> is a self-closing tag with no inner text.
getText() on an input → "" (empty)getAttribute("value") insteadid="welcome-msg" • getText() works perfectly
id="username-input" • Use getAttribute("value")
Heading:
getText(): "Welcome, User!"
Input:
getText(): ""
getAttribute("value"): "testuser_123"
Type in the input field to see how getAttribute("value") would capture it!
1234567891011121314151617// 1. Reading visible text from a heading
WebElement heading = driver.findElement(By.id("welcome-msg"));
String headingText = heading.getText();
System.out.println("Heading: " + headingText); // "Welcome, User!"
// 2. Reading value from an input field
WebElement input = driver.findElement(By.id("username-input"));
// WRONG: getText() on input returns empty string
String inputTextViaGetText = input.getText();
System.out.println("Input getText(): '" + inputTextViaGetText + "'");
// CORRECT: getAttribute("value") gets the typed text
String inputValue = input.getAttribute("value");
System.out.println("Input value: " + inputValue); // "testuser_123"
driver.quit();getText() for labels, buttons, messages.getAttribute("value") for inputs.
When text assertions fail, check if you're calling getText() on an input by mistake.
Use descriptive method names like getHeadingText() vs getUsernameValue().