13

Using selenium, can I get the text of an invisible element? I tried to do it using driver.getElement().getText() but I am getting an empty string.

<p id="versionInfo" style="display: none;">
    4.7.2<br/>
    20130714-1512
</p>
</footer></body>
djangofan
  • 28,471
  • 61
  • 196
  • 289

2 Answers2

37

Javascript is not necessary, obtain the value through the textContext attribute.

var text = driver.FindElement(By.Id("demo-div")).GetAttribute("textContent")

http://yizeng.me/2014/04/08/get-text-from-hidden-elements-using-selenium-webdriver/#c-sharp

he_the_great
  • 6,554
  • 2
  • 30
  • 28
  • This is what I am looking for instead of `getAttribute("value")`. It works well without `JavascriptExecutor`. Thanks – vkrams Jan 12 '16 at 00:57
  • Thanks for this suggestion. – 0xM4x Dec 11 '19 at 12:55
  • 1
    Works perfectly fine in Python as well using `.get_attribute('textContent')` – José Tomás Tocino Sep 16 '20 at 14:04
  • @he_the_great your solution works nicely for input elements, however, when it is a hidden select element with multiple options, all options are retrieved instead of the selected one. How can you get only the selected one on a hidden select element? – Poyson1 Mar 15 '21 at 00:08
  • @poyson1, I don't know, but I thought I observed that using the normal selected item methods ignored that the control was not displayed. I.e you don't do anything special to get selected values of hidden elements. – he_the_great Mar 17 '21 at 01:21
  • you're a saviour – Alberto Deca May 12 '21 at 11:29
5

Try javascript executor.I haven't tried it before though i was able perform click operations over invisible elements.

 JavascriptExecutor executor = (JavascriptExecutor)driver;
 String text= executor.executeScript("document.getElementById('versionInfo').innerHTML");
Karthikeyan
  • 2,634
  • 5
  • 30
  • 51