Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath find parent of a child element

I have a structure such as this:

<div class="Container">
  <div class="HighlightContainer">
    <div class="NodeTextHighlightContainer">
      <span class="TreeItemSelected">Products</span>
    </div>
    <button class="ContainerSelectedMenu" type="button"></button>
  </div>
</div>

Because of how the DOM behaves and trying to stay dynamic, I can only target the span that contains text Products. using something like:

Driver.FindElement(By.XPath("//div[contains(@class, 'Container')]/descendant::span[text() = 'Products']"));

However, I need to target the button where class="ContainerSelectedMenu" based of that span element, what is the best approach? Something like getting the parent div of the child of Container then finding the button element.

like image 708
saltillokid11 Avatar asked Dec 13 '22 18:12

saltillokid11


1 Answers

I've found different ways to do this by traversing back up and down which works fine, but my preference now is this approach:

xpath = "//div[contains(@class, 'Container') and descendant::span[text() = 'Products']]//button";

Basically, you put the descendant with text() = 'Products' as part of the requirement for the div tag you really want, which is the parent. Then you can just search for the button easily with a //button, or //button[@class='ContainerSelectedMenu']

You actually don't need the descendant axes here, so it can be simplified a bit with this:

xpath = "//div[contains(@class, 'Container') and .//span[text() = 'Products']]//button";

In English...

  • Find a div that
  • 1. has a @class that contains "Container" and
  • 2. has a descendant span element with the text `Products
  • Find a descendant of that div that is a button
like image 83
mrfreester Avatar answered Dec 17 '22 22:12

mrfreester