Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping through a collection of divs in Watir

Tags:

xpath

watir

We're using watir for testing and wondered how to select a group of divs that meet a particular criteria? In our case the (simplified) html looks like this:

<div class="month_main>
 <div class="month_cell">
   some divs
 </div>
 <div class="month_cell">
   some_other_divs
 </div>
 <div class = "month_cell OverridenDay">
   <div id = "month-2013-05-04"/>
 </div>
</div>

We would like to loop through all divs with an id starting with 'month' that are contained in month_cell parent divs that also have classes of OverridenDay. Is there an Xpath or regular expression we can use in conjunction with the Watir browser class to do this?

like image 608
larryq Avatar asked Jun 25 '13 20:06

larryq


1 Answers

General

You can get a collection of elements in a similar way to getting a single element. You basically need to pluralize the element type method. For example:

#Singular method returns first matching div
browser.div

#Pluralized method returns all matching divs
browser.divs

Collections can be used using the same locators as single elements.

Solution

For your problem, you can do:

#Iterate over divs that have the class 'month_cell OverridenDay'
browser.divs(:class => 'month_cell OverridenDay').each do |overridden_div|

    #Within each div with class 'month_cell OverridenDay',
    #  iterate over any children divs where the id starts with month
    overridden_div.divs(:id => /^month/).each do |div|

        #Do something with the div that has id starting with month
        puts div.id

    end
end
#=> "month-2013-05-0"

If you need to create a single collection that includes all of the matching divs, you will need to use a css or xpath selector.

Using a css-selector (note that in watir-webdriver, only the elements method supports css-locators):

divs = browser.elements(:css => 'div.month_cell.OverridenDay div[id^=month]')
divs.each do |e|
    puts e.id
end 
#=> "month-2013-05-0"

Using xpath:

divs = browser.divs(:xpath => '//div[@class="month_cell OverridenDay"]//div[starts-with(@id, "month")]')
divs.each do |e|
    puts e.id
end
#=> "month-2013-05-0"
like image 102
Justin Ko Avatar answered Sep 28 '22 16:09

Justin Ko