Playwright Nth Element Selector

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.

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')
});

Video Tutorial: Playwright Nth Locator