1

I have this HTMLcode:

<div class="A">
  <div class="B">
    Text1
  </div>
</div>
<div class="A">
  <div class="B">
    Text2
  </div>
</div>

So i need to find index of div class='A' where i find some text. I use Watir Webdriver and now i have this code:

if @ff.div(:class=>'A').div(:text=>'Text1')
  then ind=@ff.div(:class=>'A').index
end

but of course this doesn't work saying 'undefined local variable or method `index''.

user1116005
  • 23
  • 1
  • 4
  • 1
    What are you trying to do? What do you really need to know? Do you really need to know the index, or something else? – Željko Filipin Dec 29 '11 at 10:56
  • Agree with Zeljko here.. Tell us what you really need to do, since 'getting the index' would appear to me to be something you see as a means to an end, and there may be a much better method (for example, see my answer below) if we only knew what you were really trying to accomplish – Chuck van der Linden Dec 29 '11 at 20:48

2 Answers2

1

There's no way to get the index using the webdriver since they are relative to the collection of matched elements. What you can try to do is collect the elemetns text as Array and then get the index of the target text.

@@ff.divs(:class, 'A').collect(&:text).index('Text1')

Note that this will only work for simple scenarios (like your example). If you need to attack a more complex case update your example to match the real scenario.

Roberto Decurnex
  • 2,514
  • 1
  • 19
  • 28
1

If you are trying to get the index as a way to address the element you want to work with, and the best way to locate it is based on some attribute of a child element, then there is a better way.

e.g. if your objective was to click the instance of class A that was wrapped around the div class B with "Text1" in it, then do this

browser.div(:class => 'B', :text => 'Text1').parent.click

That's especially good for situations where the outer container you want has no useful attributes.

In your example above however, you may also simply be able to do this

browser.div(:class => 'A', :text => 'Text1').click  
Chuck van der Linden
  • 6,660
  • 2
  • 28
  • 43
  • Well, i don't want to click on this.. i want to find index of div just like in robertodecurnex's answer. – user1116005 Jan 10 '12 at 06:59
  • click was just one example of an action you could take. Really this then brings us back to the original comments to your question. "why?" what's the point of getting the index? what does that do for you? Why do you think this is 'what I need'? because if we know more about what you are trying to accomplish, we may be able to show you a better means to that end – Chuck van der Linden Jan 10 '12 at 16:29