0
driver.findElement(By.xpath(".//div[contains(text(),'Approval Date')]")).click();

The above finds the first element on the table.

There are three rows with text 'Approval Date' in the table.

How to select the third row instead of first being selected by default?

drkthng
  • 6,651
  • 7
  • 33
  • 53

2 Answers2

5

Add [last()] position index predicate after the initial xpath expression wrapped in brackets*, to get only the last matched element of the origiinal xpath :

(.//div[contains(text(),'Approval Date')])[last()]

"Also, how to select all the elements which contains 'Approval Date'"

Use findElements() -with plural 's'- to find all elements matched by the selector.

*) explanation on why the brackets are necessary: How to select specified node within Xpath node sets by index with Selenium?

Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137
2

if you want the "3rd", as you said, then you can go for [3]

driver.findElement( By.xpath(".//div[contains(text(),'Approval Date')][3]")).click();

if for example you wanted the "last" entry then go for [last()]

driver.findElement( By.xpath(".//div[contains(text(),'Approval Date')][last()]")).click();

In your case both would give back the same result...

As to your question "How to select all elements that contain "Approval Date":

List<WebElement> elements = driver.findElements( By.xpath(".//div[contains(text(),'Approval Date')]"));
drkthng
  • 6,651
  • 7
  • 33
  • 53