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.
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...
div
that @class
that contains "Container" and span
element with the text `Productsdiv
that is a button
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With