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
- Demo Website
- Use Nth Selector with CSS
- Use Nth Selector with XPath
- Use Nth Method
- Example: Select Nth Dropdown Element
- Video Tutorial
1. Demo Website
List: Use Footer List of ProgramsBuzz homepage
Dropdown: Use Interest dropdown on ProgramsBuzz Create New Account page
2. Use Nth Selector with CSS
In below code we are clicking on 0th element About Us and last element Write for us.
test.only('list nth element', async({page})=>{
await page.goto('https://www.programsbuzz.com')
// Click on About Us
await page.locator("div.block-content>ul>li>>nth=0").click()
//Click on Write for us
await page.locator("div.block-content>ul>li>>nth=-1").click()
})
3. Use Nth Selector with XPath
In below code we are clicking on 0th element About Us and last element Write for us using XPath and Nth Selector.
test.only('list nth element', async({page})=>{
await page.goto('https://www.programsbuzz.com')
// Click on About Us
await page.locator("//div[@class='block-content']/ul/li>>nth=0").click()
//Click on Write for us
await page.locator("//div[@class='block-content']/ul/li>>nth=-1").click()
})
4. Use Nth Method
In below code we are clicking on 0th element About Us and last element Write for us 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[@class='block-content']/ul/li").nth(0).click()
//Click on Write for us
await page.locator("//div[@class='block-content']/ul/li").nth(-1).click()
})
5. Example: Select Nth Dropdown Element
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')
});