Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 35 ยท Finding Elements

Locators in Playwright

Learn Playwright locators: getByRole, getByLabel, getByText, getByTestId, filter, nth, chaining and strict mode, with a runnable model of how they find elements.

In Playwright you never hold a reference to a DOM element. You hold a locator: a small description of how to find something on the page. Every time you act on it, Playwright runs that description again against the current page, waits until exactly one matching element is ready, and only then clicks, types or reads. That one design choice removes most of the "element is stale" and "element not found yet" problems that plague older browser tests.

This lesson covers the locator methods you will use every day, how to narrow a locator down with filter, nth and chaining, and what strict mode is protecting you from. If you have read Selecting Elements in Cypress, you will notice the same ideas in a different style: Cypress queries by CSS and text, Playwright prefers queries that mirror how a person or a screen reader sees the page.

Real versus stand-in. The ts code blocks show real Playwright and are read-only, because the site cannot launch a browser. The runnable examples are a small hand-written model: a fake page made of plain objects and a Locator class that implements roles, accessible names, labels and strictness. It teaches the rules, not Playwright's actual implementation.

Locators are lazy and re-evaluated

Creating a locator does not touch the page. This line finds nothing yet:

TypeScript
const addToCart = page.getByRole('button', { name: 'Add to cart' });

Only an action (click(), fill()), a read (textContent(), count()) or an assertion (expect(...).toBeVisible()) resolves it. Because the lookup is repeated on every use, you can create a locator once and reuse it across page updates, re-renders and even navigations.

flowchart LR
  A["page.getByRole(...)"] --> B["Locator (a description)"]
  B --> C["action or assertion"]
  C --> D["Resolve against the live DOM"]
  D --> E{"Exactly one match<br/>and actionable?"}
  E -- yes --> F["Perform the action"]
  E -- no --> G["Retry until the timeout"]
  G --> D

A locator is resolved fresh on each use, and the action retries until one element qualifies or time runs out.

Playwright's own advice is to prefer locators that describe what the user perceives. In rough order of preference:

TypeScript
// 1. Role plus accessible name: the best default
page.getByRole('button', { name: 'Add to cart' });
page.getByRole('heading', { name: 'Shop', level: 1 });
page.getByRole('link', { name: /^cart/i });
page.getByRole('checkbox', { name: 'Gift wrap', checked: true });

// 2. Form fields by their label
page.getByLabel('Search');
page.getByPlaceholder('Find a product');

// 3. Visible text, for non-interactive content
page.getByText('Free shipping on orders over $50');

// 4. Images and tooltips
page.getByAltText('Company logo');
page.getByTitle('Close dialog');

// 5. A test id, when nothing user-facing is stable
page.getByTestId('order-summary');

getByRole matches the element's ARIA role, either explicit (role="tab") or implicit (a <button> is a button, an <a href> is a link, <h1> to <h6> are heading). The name option filters by accessible name: the text a screen reader would announce, which comes from the element's content, an aria-label, or its <label>. Name matching is a case-insensitive substring by default; pass exact: true for a full, case-sensitive match, or pass a regular expression for patterns. Role-based locators double as a cheap accessibility check: if you cannot find your button by role and name, a screen-reader user probably cannot either.

getByLabel finds form controls through their associated label text, which is exactly how a person finds them. getByText matches the smallest element containing the text and also ignores case and extra whitespace unless you pass exact: true. Use it for headings, messages and static content, not for buttons that have a role.

getByTestId looks up the data-testid attribute. It is deliberately a last resort for user-facing locators, but it is the right tool for containers that have no role or text of their own. You can change the attribute name in the config with testIdAttribute (for example to data-cy if you are migrating from Cypress).

CSS and XPath still work

page.locator() accepts CSS selectors, XPath and several engines. It is your escape hatch.

TypeScript
page.locator('li');                       // CSS
page.locator('.price');                   // CSS class
page.locator('css=ul > li:first-child');  // explicit engine
page.locator('xpath=//li[@data-id="7"]'); // XPath
page.locator('text=Coffee');              // older text engine

Use these when there is no accessible alternative, and read Writing Selectors That Do Not Break before you reach for class names or long XPath chains.

Narrowing down: chaining, filter, nth

A locator can be refined with further locators. Chaining searches inside the elements matched so far.

TypeScript
const rows = page.getByTestId('row');

// The Add button inside the row that mentions Coffee
await rows
  .filter({ hasText: 'Coffee' })
  .getByRole('button', { name: 'Add to cart' })
  .click();

// Rows that contain a "Sold out" button
const soldOut = rows.filter({ has: page.getByRole('button', { name: 'Sold out' }) });
await expect(soldOut).toHaveCount(1);

// Rows that do NOT mention Tea
const notTea = rows.filter({ hasNotText: 'Tea' });
  • filter({ hasText }) keeps elements whose text contains the string or matches the regular expression. hasNotText does the opposite.
  • filter({ has }) keeps elements that contain a descendant matching another locator. hasNot negates it.
  • first(), last(), nth(i) pick by position (zero-based). Position is fragile if rows can be reordered, so prefer filter when you can say which row you mean.
  • and() and or() combine two locators for the same element, or accept either of two possibilities (handy for a cookie banner that may or may not appear).
  • all() returns an array of locators, one per current match, and count() returns how many there are right now.

Strict mode

Playwright's actions are strict: if a locator matches more than one element, the action throws instead of silently picking the first. With three "Add to cart" buttons on the page, this fails:

TypeScript
await page.getByRole('button', { name: 'Add to cart' }).click();
// Error: strict mode violation: getByRole('button', { name: 'Add to cart' }) resolved to 3 elements

That error is a feature. A test that clicks "whichever came first" passes today and fails mysteriously when the page order changes. The fix is to make the locator more specific (scope it to a row, add a name, use a test id), or, only when you truly mean it, call first() or nth(). Assertions like toHaveCount() and methods like count() and all() are the legitimate way to work with many elements.

A runnable model of locators

The model below builds a fake page and implements the core rules: roles from tags, accessible names from content and labels, case-insensitive substring matching, exact, scoping by chaining, filter, nth and strictness. Read the output line by line against the code.

JS A tiny locator engine over a fake page

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice three things. The substring rule makes name: 'add' match two buttons, and exact: true matches none because the real name is "Add to cart". The chained locator coffeeRow.getByRole('button') succeeds because scoping to one row leaves exactly one button. And the last two lines show the two failure modes: too many matches (strict mode) and none at all (in real Playwright this is a timeout after retrying, not an instant error).

Locators and assertions

Locators pair with web-first assertions, which retry until they pass. You will meet them properly in Assertions That Retry.

TypeScript
import { test, expect } from '@playwright/test';

test('adds coffee to the cart', async ({ page }) => {
  await page.goto('/shop');

  const coffee = page.getByTestId('row').filter({ hasText: 'Coffee' });
  await coffee.getByRole('button', { name: 'Add to cart' }).click();

  await expect(page.getByRole('link', { name: 'Cart (1)' })).toBeVisible();
});

Notice there is no sleep and no manual wait. The locator's retry loop and the assertion's retry loop do the waiting.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does creating a locator with page.getByRole('button') do?

    A locator is lazy. Nothing is looked up until an action or assertion runs, and each use resolves the description against the current page again.
  2. 2. Three buttons are named "Add to cart". What happens on await page.getByRole('button', { name: 'Add to cart' }).click()?

    Actions are strict. A locator that resolves to several elements throws, so you must narrow it down (scope it, filter it) or choose deliberately with first(), last() or nth().
  3. 3. Which locator is the best default for a button that says "Save"?

    Role plus accessible name mirrors how users and assistive technology find the control, and it survives CSS and layout refactors. Class names and XPath tied to structure break easily.
  4. 4. What does the name option of getByRole do by default?

    Name matching is a case-insensitive substring unless you pass exact: true or a regular expression.

Summary

  • A Playwright locator is a lazy description, re-resolved on every action, so it never goes stale.
  • Prefer getByRole with a name, then getByLabel, getByText, and finally getByTestId; use locator() with CSS or XPath as an escape hatch.
  • Narrow with chaining, filter({ hasText, has }) and, last of all, nth().
  • Strict mode turns an ambiguous locator into an immediate, readable error instead of a flaky click.
  • The model in this lesson implements roles, names, labels, scoping and strictness so you can see the rules at work; it is not Playwright's real engine.

Next: Writing Selectors That Do Not Break.