Playwright locator scoping with `locator.within()`
Introduced 2026-10-07 · score 0.99
HOW TO USE IT
When an element must be located relative to a dialog or separately within each matching parent, combine existing locators with `locator.within()` and perform the action on the result.
const saveButton = page.getByRole('button', { name: 'Save' });
const dialog = page.getByTestId('settings-dialog');
await saveButton.within(dialog).click();const thirdColumn = page.getByRole('cell').nth(2).within(page.getByRole('row'));
await expect(thirdColumn).toHaveText(['Apple', 'Banana', 'Cherry']);WHY THIS HELPS
Locate and act on an element relative to a dialog or independently within each matching parent.
REQUIREMENTS AND LIMITATIONS
- Version: v1.64.0
- locator.within(locator) (required): Returns a locator matching this locator's elements inside each element matched by the argument locator.
- locator.nth(index): Returns the zero-based n-th matching element; with `within()`, it resolves separately inside each matched parent.
- getByRole(role, options): Creates a locator by ARIA role; the example uses the `button` role and `name: 'Save'`.
- getByTestId(testId): Creates a locator by test id; the example uses `settings-dialog`.
- Prerequisite: Use Playwright v1.64 or later; `locator.within` was added in v1.64.
FIRST-PARTY EVIDENCE
- https://github.com/microsoft/playwright/releases/tag/v1.64.0
- https://playwright.dev/docs/api/class-locator#locator-within
- https://playwright.dev/docs/api/class-locator#locator-nth
- https://playwright.dev/docs/api/class-locator
Check the installed version and the source before using it. Entry JSON