NewTester
NewTester

Reputation: 301

Watir-webdriver : Accessing elements using Indexing

I am trying to access a li element using indexing

<div class="item-list">
<ul>
<li class="views-row views-row-1 views-row-odd views-row-first">
<li class="views-row views-row-2 views-row-even">
<li class="views-row views-row-3 views-row-odd">
<li class="views-row views-row-4 views-row-even">
<li class="views-row views-row-5 views-row-odd">
<li class="views-row views-row-6 views-row-even">
<li class="views-row views-row-7 views-row-odd">
<li class="views-row views-row-8 views-row-even">
<li class="views-row views-row-9 views-row-odd views-row-last">
</ul>
</div>

The code I am using is

@browser.div(:class,'item-list').ul.li(:index => 2)

The question is : These are elements on a page and I will be using a loop to access each element. I thought using indexing will solve the problem but when I write my code and execute it I get the following error

expected #<Watir::LI:0x2c555f80 located=false selector={:index=>2, :tag_name=>"li"}> to exist (RSpec::Expectations::ExpectationNotMetError)

How can I access these elements using Indexing.

Upvotes: 2

Views: 5551

Answers (2)

adam reed
adam reed

Reputation: 2024

If you've got class-naming that nice, forget indexing! Do a partial match on the "views-row" parameter:

@browser.li(:class => /views-row-1/)

This can easily be parameterized for looping (although I don't know what you're doing with the information so this loop will not be very exciting).

x = 0
until x==9
  x+=1
  puts  @browser.li(:class => /views-row-#{x}/).text
end

You could also blindly loop through the li's contained in your div if you'd like:

   @browser.div(:class,'item-list').lis.each do |li|
      puts li.text
   end

Upvotes: 4

Mark Thomas
Mark Thomas

Reputation: 37507

According to the Watir wiki, Watir supports the :index method on the li element. So unless it is a bug in watir-webdriver, I think the index should work.

You may want to try the watir mailing list to see if this is a problem for others.

Upvotes: 2

Related Questions