Ragnarsson
Ragnarsson

Reputation: 1825

Click checkbox with Nested Elements in Watir

I'll try to keep it simple.

I have a list of similar rows like this:

enter image description here

HTML code:

<li ...>
    <div ... >
        <some elements here>
    </div>
    <input id="121099" class="containerMultiSelect" type="checkbox" value="121099" name="NodeIds">
    <a ...>
        <div ... />
        <div ... >
            <h2>Identified Text</h2>
            <h3>...</h3>
        </div>
    </a>
</li>

I want to click the checkbox with a certain text, but I can't use any of its elements, because they are the same for all the list, and id is generated automatically. The only thing can be differentiated is the h2 text. I tried :

browser.h2(:text => /Identified/).checkbox(:name => "NodeIds").set

and I got UnknownException which is obvious because checkbox is not nested with a tag.

What can I do in this case?

Thanks

Upvotes: 1

Views: 626

Answers (2)

Justin Ko
Justin Ko

Reputation: 46836

The h2 and checkbox are related by the li, which is a common ancestor. Therefore, to find the checkbox, you can look for the li that contains the h2 element. I find the most readable approach to doing this is by using the find method of the element collection. The find method basically allows you to make custom locators.

The code would be:

parent_li = browser.lis.find do |li|
    li.h2(:text => 'Identified Text').present?
end
parent_li.checkbox.set

Notes:

  • browser.lis creates a collection of all li elements.
  • find iterates through the lis and returns the first element that has the block evaluate as true - ie the first li where an h2 with the specified text is present.

Upvotes: 2

Archit
Archit

Reputation: 176

First have a look at this explanation http://jkotests.wordpress.com/2012/12/20/finding-a-parent-element-that-matches-a-specific-criteria/

Now following a similar approach,

First locate the element that has a unique identifier

[email protected](:text=>"Identified Text")

Now we have to iterate over to the parent element which contains both the checkbox and text against it.

parent=parent.parent until parent.tag_name=="li"

Once the control is on the li element, simple click on the checkbox using.

parent.checkbox.click

Upvotes: 2

Related Questions