Playwright locators: a practical guide with exercises

9 min read · TypeScript · 13 linked exercises

A locator tells Playwright how to find an element. Choose well and your tests keep passing through redesigns and refactors. Choose badly and they break whenever a class name or the layout changes.

This guide covers which locator to use, in order of preference, and what to do when the first choice matches too much. Each section links to an exercise where you can try it on a real page.

Start with getByRole

Most elements have a role, such as button, link, checkbox or heading, and an accessible name, usually their visible text or their label. getByRole finds elements the way a user or a screen reader does, so it survives changes to the markup and styling.

await page.getByRole('button', { name: 'Save' }).click();
await page.getByRole('link', { name: 'Pricing' }).click();
await expect(page.getByRole('heading', { name: 'Your cart' })).toBeVisible();
await page.getByRole('checkbox', { name: 'Remember me' }).check();

A role locator also tells you something about the page. If you can't find a button by its role and name, a screen reader user probably can't either. That's an accessibility bug worth reporting.

Roles can also match state: { checked: true }, { expanded: true }, { selected: true }, { pressed: true } and, for headings, { level: 2 }. A selected tab, an open accordion item or a toggled formatting button can then be found without reading any classes.

Practise it
  • ButtonsBeginnerClick, double-click and right-click buttons found by role.
  • ARIA WidgetsIntermediateTabs, accordions and toggle buttons, found by their ARIA state.
  • Accessibility TreeBeginnerLinks that aren't links, and names that come from hidden text or other elements.

Names match as substrings

By default the name is a case-insensitive substring match. name: 'Click me' also matches "Double click me" and "Right click me". Playwright then refuses to click and reports a strict mode violation, because it can't know which one you meant.

// Matches "Delete", "Delete all" and "Undo delete"
page.getByRole('button', { name: 'Delete' });

// Matches only "Delete"
page.getByRole('button', { name: 'Delete', exact: true });

// A regular expression gives you full control
page.getByRole('button', { name: /^delete$/i });

exact: true makes the match whole-string and case-sensitive. Radio buttons and checkboxes catch people out most often, because their name includes the whole label. In a billing question, a "Free" plan radio also matches "Yearly, two months free".

Practise it
  • Locator ChallengesIntermediateClick "Delete" without hitting "Delete all" or "Undo delete".
  • Multi-step FormAdvancedChoose a plan when one radio label contains another.

Labels, text, placeholders and test ids

When an element has no useful role, choose the next most user-facing locator:

LocatorUse it forBreaks when
getByRoleButtons, links, form fields, headings, rowsThe visible name changes
getByLabelForm fields that have a labelThe label text changes
getByPlaceholderInputs with no label, such as a search boxThe placeholder changes
getByTextMessages and plain text without a roleThe copy is edited
getByAltText, getByTitleImages, icon buttons with a titleThe alt or title text changes
getByTestIdElements with no good accessible nameRarely, but the app must add data-testid
locator('css')The last resortAlmost any markup change

Test ids are stable, but a user never sees them. A test that only uses test ids can pass while the button's label is wrong or missing. Use them where nothing user-facing works, not everywhere.

getByLabel is a substring match too: getByLabel('Password') also finds "Confirm password". Add { exact: true } there as well.

Practise it
  • Locator ChallengesIntermediateA search box and an icon button with no text label.
  • DropdownBeginnerNative selects by label, and a custom dropdown by role.

Filter and chain instead of using CSS

Real pages repeat things: a Save button in every panel, a Delete button in every row. Find the container first, then look inside it.

// The row that mentions Michael, then the Delete button inside it
const row = page.getByRole('row').filter({ hasText: 'Michael' });
await row.getByRole('button', { name: 'Delete' }).click();

// A card that contains a specific heading
const card = page
  .getByRole('listitem')
  .filter({ has: page.getByRole('heading', { name: 'Blue Mug' }) });
await card.getByRole('button', { name: 'Add to cart' }).click();

// A named region (a <section> with an accessible name)
const panel = page.getByRole('region', { name: 'Notification settings' });
await panel.getByRole('button', { name: 'Save' }).click();

filter({ hasText }) keeps elements whose text contains a string. filter({ has }) keeps elements that contain another locator. Both have opposites: hasNotText and hasNot. A filter is checked again each time you use the locator, so it still works after the list re-renders.

Text changes in edit mode. When a row's name turns into an input, its text is now an input value, which hasText doesn't see. Filter by the textbox the row contains instead.

Practise it
  • Basic TableBeginnerFind a row by its content and read a cell by column name.
  • Table ActionsIntermediateEdit and delete rows with the buttons inside them.
  • Locator ChallengesIntermediateProducts, panels and tasks that share their text.

Combine locators: or(), and() and visible

Some elements change between visits, and some are only unique when two conditions hold. Three tools cover most of these cases:

// One of two buttons, such as in an A/B test
const signUp = page
  .getByRole('button', { name: 'Sign up' })
  .or(page.getByRole('button', { name: 'Create account' }));

// Both conditions: a Download button with a specific tooltip
const pdf = page.getByRole('button', { name: 'Download' }).and(page.getByTitle('PDF'));

// The visible copy of an element the page renders twice
const menu = page.getByTestId('user-menu').filter({ visible: true });

or() is still strict: if both sides match at once, it matches two elements. Role locators already skip hidden elements, so filter({ visible: true }) is mostly for test ids, text and CSS.

hasNotText matches a substring of all the text in an element, ignoring case. To exclude rows with an "Unread" badge, hasNot: page.getByText('Unread', { exact: true }) is safer: it ignores a subject that only mentions the word.

Practise it
  • Locator LogicIntermediateAn A/B button, a sync that may fail, an inbox to filter and a header rendered twice.

Strict mode, nth() and why to avoid it

An action on a locator that matches more than one element fails with a strict mode violation. The error lists every match, so it tells you exactly how to make the locator more specific. Read it before reaching for first() or nth().

Error: strict mode violation: getByRole('button', { name: 'Save' }) resolved to 2 elements:
    1) <button>Save</button> aka getByRole('region', { name: 'Profile' }).getByRole('button')
    2) <button>Save</button> aka getByRole('region', { name: 'Notification settings' }).getByRole('button')

nth(1) means "the second match, whatever it is". When the order changes, because of sorting, a new item or a re-render, the test acts on the wrong element and may still pass. Prefer a filter that describes the element you want. Keep nth() for cases where position is the point, such as "the first search result".

Assertions that count are not strict: await expect(page.getByRole('row')).toHaveCount(5) expects several matches on purpose.

Practise it
  • Reading FailuresBeginnerRead a real strict mode violation and fix the test from it.
  • Flaky LabAdvancedWatch nth() pick the wrong item in a list that reshuffles.

Shadow DOM and iframes

Role, text and CSS locators look inside open shadow roots automatically, so web components need no special syntax. XPath doesn't cross shadow boundaries, which is one more reason to avoid it. Nothing can look inside a closed shadow root: use the host element's attributes, or click inside its bounding box.

Iframes are different. A page locator never finds anything inside a frame. You enter the frame first with contentFrame() or frameLocator(). The iframes guide covers this.

Practise it
  • Shadow DOMIntermediateFollow a user inside a web component, and handle a closed root.

Let Playwright suggest a locator

You don't have to write every locator by hand. Run npx playwright codegen https://playwright-playground.com and click around: codegen records each action with the locator it would choose, usually a role locator. In UI mode (npx playwright test --ui) the locator picker shows the locator for any element you hover.

Treat the suggestions as a first draft. Codegen picks a locator that is unique right now. It doesn't know which parts of the page change, so check that each name is something that stays the same in every run.

Practise it
  • Debugging ToolkitAdvancedRecord a flow with codegen and compare its locators with yours.

Exercises in this guide

More guides