Get the Text of a Hidden Element
Read text that getText() returns empty for: collapsed sections, off-screen items, and elements with display:none.
Stable Verified against Selenium 4.48.0
Problem
getText() returns an empty string for an element that is present but not displayed, such as a collapsed accordion panel or a hidden validation message. You need the text without changing the page.
Solution
Read the textContent (raw DOM text) or innerText (rendered text, respects CSS) property instead of calling getText().
textContent and innerText
Selenium 3 & 4 Stable
WebElement panel = driver.findElement(By.id("terms-panel"));
// getText() -> "" when hidden. Read the DOM property instead:String raw = panel.getDomProperty("textContent"); // Selenium 4.x: getDomPropertyString rendered = panel.getDomProperty("innerText"); // respects CSS visibility rules
// Older bindings: getAttribute works for bothString legacy = panel.getAttribute("textContent");panel = driver.find_element(By.ID, "terms-panel")
raw = panel.get_dom_attribute("textContent") or panel.get_property("textContent")rendered = panel.get_property("innerText")
# Or with JavaScript for full controlraw = driver.execute_script("return arguments[0].textContent;", panel).strip()const panel = await driver.findElement(By.id('terms-panel'));
const raw = await panel.getProperty('textContent');const rendered = await panel.getProperty('innerText');var panel = driver.FindElement(By.Id("terms-panel"));
var raw = panel.GetDomProperty("textContent");var rendered = panel.GetDomProperty("innerText");Why It Works
getText() is specified to return the rendered text, which excludes hidden content by design. textContent is the concatenation of all text nodes regardless of styling; innerText applies CSS rules but, unlike getText(), is available even when the element itself is not displayed in some browsers.
Gotchas
textContentincludes text from<script>and<style>children and preserves whitespace; calltrim()and expect newlines.- If the text is empty even with
textContent, the content is not in the DOM yet (lazy rendered). Expand the section or wait for the data. - Prefer
getText()for assertions on what a user sees; this recipe is for reading data, not verifying visibility.