Take the 2-minute tour ×

There is a div on a page that is not visible but has some value I want to capture. Calling text on it returns me an empty string.

How do I get the value displayed without having to deal with the raw html? Can I force .text to return me the actual value regardless of the visiblity of the text in the browser?

irb(main):1341:0> d.first.visible?
=> false

irb(main):1344:0> d.first.html
=> "<div class=\"day\">7</div>"

irb(main):1345:0> d.first.text
=> ""

PS: There are many many divs (the page is caching response and display them accordingly). I considered changing all the display:none in the page or clicking to make them visible but I'd prefer to avoid this if possible. If not possible a solution with changing all the display none would be the preferred work around.

PPS: Damned, I tried to overload the visible? method in the Watir::Element class to always return true, but that didn't do the trick.

irb(main):1502:0> d.first.visible?
=> true

irb(main):1504:0> d.first.text
=> ""
share|improve this question
Are you using watir-classic, watir-webdriver or both? While the behaviour is the same in both gems, I think the workaround would be different. –  Justin Ko Feb 7 '13 at 14:08
gem 'watir-webdriver' using firefox –  Jeremy Feb 7 '13 at 17:01
What about parsing that HTML? –  A.D. Feb 8 '13 at 12:36
That's what I do but that's not correct to spread HTML syntax knowledge to the user of this gem. Not to mention maintenance efforts with regex. The lib should really have something like innerHtml that should not care about visible or not, since I can query that myself. The text/value function has some extra built-in intelligence that should not be there. –  Jeremy Feb 8 '13 at 14:35
@Jeremy I agree, maybe @ŽeljkoFilipin will know more.. Regex? stackoverflow.com/q/1732348/1136008 Use f.e. Nokogiri: value = Nokogiri::HTML("<div class=\"day\">7</div>").text # => "7" –  A.D. Feb 8 '13 at 16:29

1 Answer 1

up vote 6 down vote accepted

I think you have to use javascript to get this.

e = d.first
browser.execute_script('return arguments[0].textContent', e)
#=> "7"

Note that this would only work for Mozilla-like browsers. For IE-like browsers, you would need to use innerText. Though if you are using watir-classic it would simply be d.first.innerText (ie no execute_script required).

Update - Using attribute_value:

Turns out you can make it simpler by using the attribute_value method. Seems it can get the same attribute values as javascript.

#=> "7"
share|improve this answer
Clever work around! Thanks Justin. That did the trick indeed. It's quite verbose but works. Thanks. I'll accept the answer if no one come up with a more clever answer, but you got my +1 for sure! Many thanks. –  Jeremy Feb 8 '13 at 19:20
If you need to do this often, you could always add it as a method to the Element class. –  Justin Ko Feb 8 '13 at 20:51

Your Answer


