GIVEN the following WATIR object:
my_links["Reports"]
=> #<Watir::Anchor: located: true; {:tag_name=>"a", :index=>8}>
The tag_name
is easy to retrieve:
my_links["Reports"].tag_name
2018-10-12 12:29:00 INFO Watir <- `Verifying precondition #<Watir::Anchor: located: true; {:tag_name=>"a", :index=>8}># for tag_name`
2018-10-12 12:29:00 INFO Watir <- `Verified precondition #<Watir::Anchor: located: true; {:tag_name=>"a", :index=>8}>#assert_exists`
2018-10-12 12:29:00 INFO Watir -> `Executing #<Watir::Anchor: located: true; {:tag_name=>"a", :index=>8}>#tag_name`
2018-10-12 12:29:00 INFO Watir <- `Completed #<Watir::Anchor: located: true; {:tag_name=>"a", :index=>8}>#tag_name`
=> "a"
But how do I retrieve the index number? I can see it is the integer 8
, but I can't find a method to return it.
The Hash, {:tag_name=>"a", :index=>8}
, comes from the element's selector. There is an attribute reader to access this:
my_links["Reports"].selector
#=> {:tag_name=>"a", :index=>8}
You can access the index from this Hash:
my_links["Reports"].selector[:index]
#=> 8
Note that elements retrieved via a collection will always have an index. Retrieving an individual element may not, which means the index will be nil
:
browser.link.selector
#=> {:tag_name=>"a"}
browser.link.selector[:index]
#=> nil
However, if the index isn't specified, you can assume it's zero. To avoid the nil
, provide a default value:
browser.link.selector.fetch(:index, 0)
#=> 0