Forwarding Forwarding - 3 months ago 15
Ruby Question

How can I get the number of instances of a tag element with "id='foo'" using Watir?

How can I get the number of instances of a tag element with

id='foo'
using Watir?

I have this:

b = Watir::Browser.new
b.a(:id => 'foo')


How then do I get the number of instances and access via an index, like this:

b.a(:id => 'foo', :index => $i) #Here, $i is a variable in a loop


In pseudocode I'm essentially trying to do this:

num = "number of a tags with id foo"
while $i less than num do
put b.a(:id => 'foo', :index => $i).text into an array
end


I know how to do everything above EXCEPT finding
num
.

Answer

If you want to know how many matches there are, you need to get an element collection (not just an element). A collection is retrieved by pluralizing the element method - ie as.

b.as(:id => 'foo')
#=> <Watir::AnchorCollection>

From the collection, you can use length (or count) to find the number of instances:

b.as(:id => 'foo').length

Note that the element collection is Enumerable. This means you do not need to use a while loop and manual track the current index and total elements. For example, using each, you can simply write:

b.as(:id => 'foo').each do |a|
  puts a.text
end