Harunhh123
Harunhh123

Reputation: 53

how to write a nested xpath xpression based on other elements in the div?

I need to find a button using xpath and want to try using a nested xpath xpression.

I've been using the expression

 @FindBy(xpath="//*/button[contains(text(),'FOO')]")

to find instances of other buttons elsewhere in the code and so far this works fine. however My code is dynamically creating multiple instances of an 'Add' button on the page and sometimes these add buttons are invisible

Is it possible to write an Xpath expression that can find a button with the text 'Add' that is inside a div that has a has a h1 containing text 'panel visible'?

Here is a redacted version of the HTML as it currently exists

<div class="foo1">
<div class="foo2">
<div class="foo3">
<div class="foo4">
<div class="foo5">
<h1 >New Contact</h1>
</div>
<div >
<div >
<div >
<span >
<button >Add</button>
</span> 

Upvotes: 1

Views: 888

Answers (2)

Harunhh123
Harunhh123

Reputation: 53

This worked, but is tightly coupled

@FindBy(xpath="//h1[contains(text(), 'Panel visible')]/../../..//button[contains(text(), 'Add')]")

This was a better answer and is more loosely coupled

(xpath="//*[contains(concat(' ', @foo, ' '), ' foo_container ')][descendant::h1[contains(text(), 'Panel visible')]]//button[contains(text(), 'Add')]") 

Upvotes: 1

Cathal
Cathal

Reputation: 1338

Try this:

//div/h1[contains(text(), 'panel visible')]/button[contains(text(), 'Add')]

Upvotes: 1

Related Questions