Get First and Last Element in Playwright Java

Profile picture for user arilio666

In Playwright java, you can select the first and last element from the list of elements using several ways. 

Let's discuss some of them in this article.

We will use this list of elements isolated to their respective heading for the Demo.

1. Find the First Element using the first method

Use the first() method of the playwright to get the first.

    page.navigate("https://www.programsbuzz.com/search/node?keys=playwright+java");

        Locator listEle = page.locator("//h3[@class='search-result__title']");

        listEle.first().click();

Doing this will click the first element from the list of topics.

2. Find the First Element using Nth Method

Use the nth() method of playwright with index 0.

    page.navigate("https://www.programsbuzz.com/search/node?keys=playwright+java");

        Locator listEle = page.locator("//h3[@class='search-result__title']");

        listEle.nth(0).click();

We can also provide the other topic indexes present on the page.

3. Find the Last Element using the last method

Use the last() method of the playwright to get the last element.

page.navigate("https://www.programsbuzz.com/search/node?keys=playwright+java");

        Locator listEle = page.locator("//h3[@class='search-result__title']");

        listEle.last().click();

4. Find the Last Element using Nth Method

Use the nth() method of playwright with index -1.

    page.navigate("https://www.programsbuzz.com/search/node?keys=playwright+java");

        Locator listEle = page.locator("//h3[@class='search-result__title']");

        listEle.nth(-1).click();