0

I have a HTML like this:

<div class="classDiv">
  <header>
    <button class="btn btn-icon-only btn-icon-only pull-right ng-scope" type="button">
   <span class="btn-box">
     <span class="sr-only">Edit</span>
  <span class="icon-btn icon-edit2" aria-hidden="true"></span>
   </span>
    </button>
    <h3 class="classH3">Text1</h3>
  </header>
</div>
<div class="classDiv">
  <header>
    <button class="btn btn-icon-only btn-icon-only pull-right ng-scope" type="button">
   <span class="btn-box">
     <span class="sr-only">Edit</span>
  <span class="icon-btn icon-edit2" aria-hidden="true"></span>
   </span>
    </button>
    <h3 class="classH3">Text2</h3>
  </header>
</div>

The problem is every tag is the same, only the text of H3 is different for each div. I want to click only one particular Edit button, for example the second Edit button.

So I tried to find second H3 and from there I tried to find the second Edit button, like this:

WebElement hText = webDriver.findElement(By.xpath("//h3[contains(., 'Text2')]"));
WebElement editBtn = hText.findElement(By.xpath("//button[contains(., 'Edit')]"));
editBtn.click();

But it always clicks on the first Edit button. I want to find the parent element, and from parent to find its child. But in this case, every tag is the same, so I don't know how to look for a particular child. Any help much appreciated

Ragnarsson
  • 1,715
  • 7
  • 41
  • 74

2 Answers2

0

If I don't remember bad (//button)[1] or (//button)[2] let you select the button based on his position on the returned list of button

Filippo Fratoni
  • 379
  • 2
  • 7
0

try this one:

WebElement divWithH3 = webDriver.findElement(By.xpath("div[.//h3[contains(., 'Text2')]]"));
WebElement editBtn = divWithH3.findElement(By.xpath("//button[.//span[contains(text(), 'Edit')]]"));
editBtn.click();

This first finds the div element that contains your "Text2" element. From there you are searching for a button element, that has a span element that contains the text "Edit"

drkthng
  • 6,651
  • 7
  • 33
  • 53