Watir: How to find an element in which this class and the class of one of his parents identifies him?
I have html like
<div class="header"><div class="title">AAAAAAAAA</div></div> <div class="body"> <div class="card"><div class="xxx"><div class="yyy"><div class="title">AAAAAAAAA</div></div></div></div> <div class="card"><div class="xxx"><div class="yyy"><div class="zzz"><div class="title">BBBBBBBBB</div></div></div></div></div> </div> What do I need to do to say (via watir-webdriver) “to get me an element with the class“ title ”and with the text“ AAAAAAAAA ”, which is a child of the element with the“ class card. ”In this example, I want to find a div with the class title in the third line.
It’s not enough to say “give me the element with the text“ AAAAAAAAA ”and the class“ title ”, because this element can exist somewhere else in the DOM. I must be able to identify it by its attributes and my parents.
I'm not sure how to do this, and I really like some suggestions.
In watir-webdriver, if I write:
b.element(:class => "card").element(:class => "title", :text => "BBBBBBBBB") Then, from what I saw, nothing will be found, since the element (: class => "card") will correspond to the first element of the map, on line 3, and then a match for BBB ... the text will fail because it the only AAA ... that is available under the first card.
I'm at least something like
b.elements(:class => "card").each { |elem| ...etc } to find the child that I am following it, but when I find the child, I cannot use it easily. For example, I want to be able to call visible? on this, but the result is hard to get out of this code block. Could I have a local variable that I set to visible? result, or I could throw an error from within the block, but that’s not quite what I need.
What am I really after this:
b.elements(:class => "card").element(:class => "title", :text => "BBBBBBBBB").othermethods... Thus, the first call to the method finds all the elements with the map class, and then in the second method it finds the first element under those maps that have the "title" class and the text "BBBBBBBBBB". I know that under the card there will be only one element with the class heading and the text "BBBBBBBBBB".
However, this functionality does not exist. Is there an easy way to achieve the same? I would really appreciate a little guidance. Thanks in advance.
I won’t be surprised if Justin or Zhelko come up with the best solution for you (and if they do, I would like to know what it is, I!), But here is something that, being ugly, should suffice:
target_parent_div = b.divs(class: "card").find { |div| div.div(class: "title", text: "AAAAAAAAA").exists? } target_element = target_parent_div.div(class: "title", text: "AAAAAAAAA") ... Then use target_element for what you need.