nth, first, and last Locators
nth, first, and last Locators: definition, detailed explanation, practical usage, examples, mistakes, interview notes, and practice for Playwright automation.
Definition and Brief Explanation
Definition: nth(), first(), and last() choose an element by position from a locator result.
Explanation: Positional locators are useful when order is the behavior being tested, such as the first search result. They should not be used to hide strict mode problems when a better unique locator is possible.
Why It Matters
- It makes tests easier to read because the locator describes the target element clearly.
- It reduces flaky failures caused by layout changes or generated CSS classes.
- It works with Playwright auto-waiting, so actions and assertions wait for the element state.
- It supports maintainable Page Object Model code because selectors are meaningful.
How It Works
- Identify the element by user-facing meaning first: role, label, text, placeholder, alt text, or title.
- Confirm the locator points to the intended element and is unique when used for an action.
- Use filters, chaining, or test ids when the page has repeated controls.
- Avoid positional locators unless order is the behavior being tested.
Syntax and Examples
Example 1: First item
await page.locator('.search-result').first().click();
Explanation: Clicks the first result when the first result is the requirement.
Example 2: Third item
await page.locator('.search-result').nth(2).click();
Explanation: nth is zero-based, so nth(2) means the third matching element.
Common Mistakes
- Using generated CSS classes as the first option.
- Using broad text that appears in many places.
- Adding nth() only to silence strict mode.
- Storing element handles instead of using locators.
Interview Notes
- What does nth, first, and last Locators mean in Playwright?
- When would you choose nth, first, and last Locators?
- How do you make the locator unique?
- What makes this locator stable or unstable?
Practice Task
Create a small Playwright example for nth, first, and last Locators. Add one positive assertion, one note about what can go wrong, and one improvement that would make the test more maintainable.