How can I get the number of instances of a tag element with
id='foo'
b = Watir::Browser.new
b.a(:id => 'foo')
b.a(:id => 'foo', :index => $i) #Here, $i is a variable in a loop
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
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
.
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