# Locators > **When to use**: Every time you need to find an element on the page. Start here before reaching for CSS or XPath. > **Prerequisites**: [core/configuration.md](configuration.md) ## Quick Reference ```typescript // Priority order — use the first one that works: page.getByRole('button', { name: 'Submit' }) // 1. Role (default) page.getByLabel('Email address') // 2. Label (form fields) page.getByText('Welcome back') // 3. Text (non-interactive) page.getByPlaceholder('Search...') // 4. Placeholder page.getByAltText('Company logo') // 5. Alt text (images) page.getByTitle('Close dialog') // 6. Title attribute page.getByTestId('checkout-summary') // 7. Test ID (last semantic option) page.locator('.legacy-widget button') // 8. CSS/XPath (last resort) ``` ## Recent Locator Helpers (Playwright 1.59+) > Playwright 1.60 also adds a `description` option to `getByRole()` for disambiguating controls with the same name — see [Role-Based Locators](#disambiguating-by-accessible-description-description-playwright-160) below. Playwright 1.59 added two useful locator-discovery helpers: - Interactive locator picking for debugging and exploration - `locator.normalize()` for rewriting brittle selectors toward Playwright best practices Use these during debugging, refactors, and authoring. Do not treat them as a substitute for thinking through the most user-facing locator yourself. The best production locator is still usually `getByRole()`, `getByLabel()`, or `getByTestId()` when semantics are unavailable. ### `page.pickLocator()` For Interactive Discovery **Use when**: You are exploring a page, debugging a selector, or migrating a legacy suite and want Playwright to suggest a locator for the element under your cursor. **Avoid when**: Writing final production tests without review. Treat the picked locator as a starting point, not the final answer. **TypeScript** ```typescript import { test } from '@playwright/test'; test('pick a locator during debugging', async ({ page }) => { await page.goto('/checkout'); const picked = await page.pickLocator(); console.log(picked); await page.cancelPickLocator(); }); ``` **JavaScript** ```javascript const { test } = require('@playwright/test'); test('pick a locator during debugging', async ({ page }) => { await page.goto('/checkout'); const picked = await page.pickLocator(); console.log(picked); await page.cancelPickLocator(); }); ``` Review the suggested locator before keeping it. Prefer rewriting it to `getByRole()` or another semantic locator if that makes the test clearer. ### `locator.visible()` For Visible-Only Matching (Playwright 1.63+) `locator.visible()` returns a locator narrowed to visible elements only. It replaces the `:visible` CSS pseudo-class, which was Playwright-specific syntax that only worked inside `locator()` strings and could not be chained onto a semantic locator. ```javascript await page.locator('button').visible().click(); ``` **Use it for genuinely duplicated UI**, not to paper over strict-mode violations. A responsive layout that renders both a desktop nav and a mobile nav, hiding one by media query, is the real case: both match `getByRole('link', { name: 'Settings' })`, exactly one is visible, and `.visible()` says so directly. ```javascript // Responsive layout renders both navs; only one is visible at this viewport await page.getByRole('link', { name: 'Settings' }).visible().click(); ``` **When it is the wrong tool**: if two visible elements match, `.visible()` does not help and you still get a strict-mode violation. Scope with chaining or `filter()` instead — see [Locator Chaining and Filtering](#locator-chaining-and-filtering). And if an element is hidden because the app has not finished rendering, `.visible()` narrows the match at query time rather than waiting for the right one to appear; assert on the expected element instead. ### `locator.within()` For Combining Two Locators (Playwright 1.64+) **Use when**: You already hold two locators, a target and a container, and want "this button, within that dialog" without rewriting either. **Avoid when**: A plain chain reads just as well: `dialog.getByRole('button', { name: 'Save' })` is still the default. **Before 1.64** you could only scope by chaining from the container: `container.getByRole(...)`. That forces you to build the target from the container, so a reusable target locator (from a page object, a fixture, or a helper) had to be re-declared for each container it lived in. **1.64** adds `target.within(container)`, which reads in the natural order and reuses both locators as they are: ```javascript const saveButton = page.getByRole('button', { name: 'Save' }); const dialog = page.getByTestId('settings-dialog'); await saveButton.within(dialog).click(); ``` **Column-like queries**: relative parts such as `nth()` or `first()` are resolved **inside each parent separately**. That turns "the third cell of every row" into one locator instead of a loop: ```javascript // The third cell of every row, not the third cell in the whole table const thirdColumn = page.getByRole('cell').nth(2).within(page.getByRole('row')); await expect(thirdColumn).toHaveText(['Apple', 'Banana', 'Cherry']); ``` Compare `page.getByRole('row').getByRole('cell').nth(2)`, which picks the third cell across the whole result set. When you mean "per row", use `within()`. ### `page.getByRef()` For Aria Snapshot Refs (Playwright 1.64+) `page.ariaSnapshot({ mode: 'ai' })` labels each element with a short ref such as `e2`. `page.getByRef('e2')` turns that ref back into a locator. This is the bridge between an agent that reads the snapshot and test code that acts on it. ```javascript const snapshot = await page.ariaSnapshot({ mode: 'ai' }); // ... an agent picks "e2" from the snapshot ... await page.getByRef('e2').click(); ``` Refs are tied to one snapshot of one page state. Use them inside agent loops and exploration scripts; in committed tests, rewrite the target as `getByRole()` so the test survives a re-render. ### `locator.normalize()` For Refactors **Use when**: You inherit brittle CSS/XPath-heavy locators and want Playwright to suggest a more idiomatic form during cleanup work. **Avoid when**: You have not yet thought through the element's semantics. A normalized locator can still be less clear than a hand-written role or label locator. **TypeScript** ```typescript import { test } from '@playwright/test'; test('normalize a legacy locator', async ({ page }) => { await page.goto('/settings'); const legacy = page.locator('.settings-panel button.save'); const normalized = await legacy.normalize(); console.log(normalized); }); ``` **JavaScript** ```javascript const { test } = require('@playwright/test'); test('normalize a legacy locator', async ({ page }) => { await page.goto('/settings'); const legacy = page.locator('.settings-panel button.save'); const normalized = await legacy.normalize(); console.log(normalized); }); ``` Use `normalize()` as a refactoring assistant. The final test should still reflect user intent, not just "whatever selector Playwright could derive." ## Patterns ### Role-Based Locators (Default Choice) **Use when**: Always. This is your starting point for every element. **Avoid when**: The element has no ARIA role and adding one is outside your control. Role-based locators mirror how assistive technology sees your page. They survive refactors, class renames, and component library swaps. **TypeScript** ```typescript import { test, expect } from '@playwright/test'; test('role-based locators cover most UI elements', async ({ page }) => { await page.goto('/dashboard'); // Buttons — matches