Modern QA2026Nth Element Selection — tiles
Log inJoin
79 / 139 · 13 Browser Automation with Playwright · Advanced Locators← prev⊞ allnext →☰ Read as one page

8.4Nth Element Selection

When multiple elements match and you need a specific one:

// First matching element
await page.getByRole('button', { name: 'Delete' }).first().click();

// Last matching element
await page.getByRole('button', { name: 'Delete' }).last().click();

// Specific index (0-based)
await page.getByRole('listitem').nth(2).click();

// Counting elements
await expect(page.getByRole('listitem')).toHaveCount(5);

Prefer Filtering Over nth()

nth() is positional and breaks when item order changes. Prefer filtering by content:

// FRAGILE: relies on position
await page.getByRole('row').nth(3).getByRole('button').click();

// RESILIENT: targets by content
await page.getByRole('row')
  .filter({ hasText: 'Order #1234' })
  .getByRole('button', { name: 'View' })
  .click();