getText() method of selenium chrome driver sometimes returns an empty string

Update: The textContent attribute is a better option and supported across the majority of browsers. The differences are explained in detail at this blog post: innerText vs. textContent

As an alternative, the innerText attribute will return the text content of an element which exists in the DOM.

element.getAttribute("innerText")

The isDisplayed() method can sometimes trip over when the element is not really hidden but outside the viewport; getText() returns an empty string for such an element.

You can also bring the element into the viewport by scrolling to it using javascript, as follows:

((JavaScriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element);

and then getText() should return the correct value.

Details on the isDisplayed() method can be found in this SO question:

How does Selenium WebDriver’s isDisplayed() method work

Leave a Comment