Search code examples
watir

How to get Watir to look for child elements


I have the following divs

<div class="item" id="123" >
  <div class="sub_item">
     ...
     <p id="456">Test</p>
  </div>
</div>

I am trying to come up with a Watir query to test it I came up with the following (I only need the first one)...

  def item_present?
    # @browser.divs(:id => /\d+/).divs.length > 0
    @browser.divs(:id => /\d+/)[0].paragraphs(:id => /\d+/).size
  end

I get an error

undefined method `paragraphs' for #<Watir::Div:0x5a428c3e>

Solution

  • To match "p" elements, the method is:

    • p for the first match or
    • ps for all matches

    So you could do:

    @browser.divs(:id => '123')[0].ps(:id => '456').size
    

    Given the method name, perhaps you actually want to be doing?

    @browser.div(:id => '123').p(:id => '456').present?
    

    Note that divs(:id => '123')[0] is the same as just div(:id => '123').