Playwright Nth Element Selector

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.

Table of Content

  1. Demo Website
  2. Nth Selector with CSS 
  3. Nth Selector with XPath
  4. Nth Method 
  5. Example: Select Nth Dropdown Element
  6. Video Tutorial

1. Demo Website

List: Use Footer List of ProgramsBuzz homepage

playwright nth selector

2. Nth Selector with CSS 

In below code we are clicking on 0th element About Us and last element Terms of Use. Use >>nth=0 for first element and >>nth=-1 for last element just after finding the selector.

test.only('list nth element', async({page})=>{
    await page.goto('https://www.programsbuzz.com')
    
    // Click on About Us
    await page.locator("div.region-footer-bottom-second ul.menu>li>>nth=0").click()
    
    //Click on Terms of Use
    await page.locator("div.region-footer-bottom-second ul.menu>li>>nth=-1").click()
})

 3. Nth Selector with XPath 

In below code we are clicking on 0th element About Us and last element Terms of Use using XPath and Nth Selector. Use >>nth=0 for first element and >>nth=-1 for last element just after finding the selector.

test.only('list nth element', async({page})=>{
    await page.goto('https://www.programsbuzz.com')

    // Click on About Us
    await page.locator("//div[contains(@class,'region-footer-bottom-second')]//ul[@class='menu']/li>>nth=0").click()

    //Click on Terms of Use
    await page.locator("//div[contains(@class,'region-footer-bottom-second')]//ul[@class='menu']/li>>nth=-1").click()
})

4. Nth Method

In below code we are clicking on 0th element About Us and last element Terms of Use using Nth Method.

test.only('list nth element', async({page})=>{
    await page.goto('https://www.programsbuzz.com')

    // Click on About Us
    await page.locator("div.region-footer-bottom-second ul.menu>li").nth(0).click()

    //Click on Terms of Use
    await page.locator("div.region-footer-bottom-second ul.menu>li").nth(-1).click()
})

5. Example: Select Nth Dropdown Element

Use Interest dropdown on ProgramsBuzz Create New Account page

playwright nth selector to select dropdown value

Let's Verify 2nd last element of Interest dropdown contains text Quality Assurance.

test.only('Verify DropDown Value', async ({page})=> 
{
    await page.goto("https://www.programsbuzz.com/user/register");
    await expect(page.locator('.form-select option').nth(-2)).toHaveText('Quality Assurance')
});
Mon, 07/04/2022 - 12:01

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

Video Tutorial: Nth Element Selector in Playwright

Tags