How do I get the number of instances of a label element with & ldquo; id = 'foo' & rdquo; using Watir?


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

I have this:

b =
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

I know how to do everything above EXCEPT finding num.

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. => 'foo')
#=> <Watir::AnchorCollection>

From the collection, you can use length (or count) to find the number of instances: => '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: => 'foo').each do |a|
  puts a.text