Nth Element Selector in Playwright Java

Profile picture for user arilio666

You can use Playwright Nth Selector when multiple elements are found on a webpage to narrow your query. You can fetch one of many elements using nth selector indexing. Unlike CSS's nth match, the nth selector index starts from 0. To select the last element, you can use index -1.

1. Demo Website

We will use the programsbuzz homepage.

2. Nth Selector

  • In the below code, we are clicking on the 6th element, "Contact." 
  • Use >>nth=6 for the sixth element.
  • Here, we isolated the element based on the tags and index using the nth.
    page.navigate("https://programsbuzz.com");
        String textContent = page.locator("div.container-fluid ul li >> nth=6").textContent();
        System.out.println(textContent);
  • We can see we isolated the element on the sixth index as needed.
page.navigate("https://programsbuzz.com");
        String textContent = page.locator("div.container-fluid ul li").nth(6).textContent();
        System.out.println(textContent);        
  • We can also get the nth element using this approach too.
  • We can also get the element out of a dropdown the same way.

        page.navigate("http://autopract.com/selenium/dropdown1/");
        String textContent = page.locator("select.custom-select option >> nth=-2").textContent();
        System.out.println(textContent);
  • Using the -2, we can get the second last element of the dropdown.