When should I use first() or nth() on a Playwright locator?
Written by Jatin Thacker, Automation Architect · Updated
This answer is one piece of Chapter 10: Locators II: Scoping and Rot.
- Scoping and Filtering
- CSS Selectors, and the Ones That Rot
- XPath, and What Replaced It
- Locators That Rot
- Locator Factories
- Practice and interview questions: Locators Masterclass
Playwright's documentation on strictness warns: "These methods are not recommended because when your page changes, Playwright may click on an element you did not intend." Index-based positional selectors like .first(), .last(), and .nth() couple tests to DOM ordering rather than user-perceived content.
When a list reorders due to sorting, dynamic updates, or randomized seeds, positional locators silently select a completely different element. In contrast, semantic locators using .filter({ hasText: '...' }) or unique test IDs target the intended business entity regardless of its position in the list.
Reserve .first() and .nth() exclusively for cases where ordinal position is the genuine specification under test, such as confirming that the most recently placed order appears at index 0 of an audit ledger.
import { test, expect } from '@playwright/test';
test('positional .first() vs semantic .filter() when item order changes', async ({ page }) => {
// With seed=42, Aurora Kettle happens to be the first item
await page.goto('/catalog.html?mock=static&seed=42');
const items = page.getByTestId('recommended-item');
await expect(items.first()).toHaveText('Aurora Pour-Over Kettle');
await expect(items.filter({ hasText: 'Aurora Pour-Over Kettle' })).toHaveText('Aurora Pour-Over Kettle');
// With seed=99, the list reorders: .first() picks a different product, but .filter() still finds the target
await page.goto('/catalog.html?mock=static&seed=99');
await expect(items.first()).toHaveText('Quarry Ceramic Dripper');
await expect(items.filter({ hasText: 'Aurora Pour-Over Kettle' })).toHaveText('Aurora Pour-Over Kettle');
});1 passed (2.1s)
page.getByRole('button', { name: 'Add to cart' }).first()?Practised in the full course: the drill When position is the identity.
See the chapterRelated questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free