Can't find element by index using XPath

Viewed 1052

I write XPath in Console to find icon element $x("//mat-icon"). Then I get list of elements:

0: <mat-icon class="mat-icon notranslate mat…-color ng-star-inserted" _ngcontent-cvb-c17="" aria-hidden="false" aria-label="start" role="img">
1: <mat-icon class="mat-icon notranslate mat…-color ng-star-inserted" _ngcontent-cvb-c17="" aria-hidden="false" aria-label="start" role="img"> 

and I want to pick the first one so I write index $x("//mat-icon[1]") but it doesn't work. However, if I write $x("//mat-icon")[1] it works, but when I write it in IDE error message appears:

driver.findElement(By.xpath("//mat-icon")[0]).click();
2 Answers

What about the following:

driver.FindElements(By.xpath("//mat-icon")).get(0).click();

I hope it helps you!

To pick the first <<mat-icon> element you can use either of the following Locator Strategies:

  • Using findElements(), and get():

    driver.findElements(By.cssSelector("mat-icon")).get(0).click();
    
  • Using findElements(), and get():

    driver.findElements(By.xpath("//mat-icon")).get(0).click();
    
  • Using findElements(), and index:

    driver.findElements(By.xpath("//mat-icon")).get(0).click();
    
Related