Reputation: 1082
I have the following HTML Structure:
<div class="items">
...some complex structure with many sub divs ...
<div id="specificchild"></div>
</div>
<div class="items>
...
</div>
and i need to get to the DIV with the class item, that contains the "specificchild"-DIV. The Problem is that the specificchild is not directly related to the parent div "items" and also the structur in between is not always the same. So
browser.div(:id => "specificchild").parent
wont work.
Is there a possibility to select the div without looping through all of them and asking if it contains the "specificchild"?
Upvotes: 2
Views: 2479
Reputation: 46826
Solution 1 - Xpath
In this case, I think the easiest solution is to use xpath:
browser.div(:xpath, '//div[@class="items"][.//div[@id="specificchild"]]')
Solution 2 - Iterating Until Parent
Alternatively, you could find the specificchild element like you normally do. Then iterate item the parents until the one with class 'items' is found:
item = browser.div(:id => 'specificchild')
item = item.parent until item.class_name == 'items'
Solution 3 - Using find
Another option is getting a collection of the divs with class items and then finding the one with the specific child. It will only iterate through the divs until the desired one is found.
browser.divs(:class => 'items').find{ |item| item.div(:id => 'specificchild').exists? }
Upvotes: 3