Playwright Locators (2026): 9 Types Tested Against a UI Change

Hands-on tested
Quick answer

start with getByRole(), use getByLabel() for form fields, and add getByTestId() where text changes often. Scope every locator to its section of the page. We tested 9 locator styles on our demo shop, then renamed one button the way a real refactor would. Five locators broke. The four that survived did so for reasons you should know before copying them.

How we tested (23 Nov 2026): @playwright/test 1.63.0 with Chromium 153, TypeScript, on our public practice site AITG Demo Shop v3.0.0 (served locally from the same files). 30 tests, run 5 times: same result every run. Not tested: Firefox and WebKit, the Python, Java and C# APIs, closed shadow roots, getByAltText(). Read how we test.

What a Playwright locator is

A locator is Playwright’s way of saying “find this element when I need it”. It is not a snapshot: Playwright looks the element up again on every action, waits until it is visible and enabled, and only then clicks or types. That auto-waiting is why most Playwright tests need no manual sleeps.

Locators are also strict. If an action’s locator matches more than one element, Playwright throws an error instead of guessing. We hit this on purpose in the test below.

The built-in locators, with code that ran

Playwright’s docs recommend role locators first, “as it is the closest way to how users and assistive technology perceive the page” (playwright.dev, checked 23 Nov 2026). Every example below passed on our demo shop.

LocatorUse it forExample from our tests
getByRole()Buttons, links, headings, dialogs, rows: anything with a rolepage.getByRole('button', { name: 'Log in' })
getByLabel()Form fields with a labelpage.getByLabel('Email')
getByPlaceholder()Inputs with no label but a placeholderpage.getByPlaceholder('Search products')
getByText()Non-interactive text: messages, paragraphsframe.getByText('Thanks! (fake, nothing was sent)')
getByTestId()Elements whose text changes, or has no rolepage.getByTestId('cart-count')
getByTitle()Elements with a title attribute, such as iframespage.getByTitle('Newsletter form')
getByAltText()Images by alt textNot tested: our shop has no images with alt text
locator()CSS or XPath, as a last resortpage.locator('button.add')

A broken locator makes a test brittle, not flaky. For tests that pass and fail with no change at all, see our flaky tests measurement.

A full login with user-facing locators only:

await page.goto('login.html');
await page.getByLabel('Email').fill('demo@aitg.test');
await page.getByLabel('Password').fill('Demo123!');
await page.getByRole('button', { name: 'Log in' }).click();
await expect(page.getByRole('link', { name: 'Log out' })).toBeVisible();

Our test: 9 locators against a button rename

Most locator guides list the types. We wanted to know which ones survive a change. The demo shop has a switch, ?rename=1, that changes the “Add to cart” button the way a refactor would: the text becomes “Add to basket”, the id changes from add-to-cart-6 to basket-add-6, and the data-testid changes from add-to-cart to basket-add.

Each test clicks the button on the “Wireless mouse” card and checks that the cart badge shows 1. We ran each locator on the normal shop and on the renamed shop.

Demo shop product card before and after the rename switch: Add to cart becomes Add to basket, and the id and data-testid change
The rename switch changes the button text, its id and its data-testid at once, like a real refactor. Screenshot from our demo shop.
const card = (page) => page.getByTestId('product-card').filter({ hasText: 'Wireless mouse' });

test('getByRole exact name', async ({ page }) => {
  await page.goto('index.html?rename=1');
  await card(page).getByRole('button', { name: 'Add to cart' }).click();
  await expect(page.getByTestId('cart-count')).toHaveText('1');
});
LocatorNormal shopAfter rename
getByRole('button', { name: 'Add to cart' })PassFail (timeout)
getByText('Add to cart')PassFail
getByTestId('add-to-cart')PassFail
CSS id #add-to-cart-6PassFail
XPath //article[.//a[text()='Wireless mouse']]//button[text()='Add to cart']PassFail
CSS class button.add inside the cardPassPass
getByRole('button', { name: /^add to (cart|basket)$/i })PassPass
getByRole('button') inside the cardPassPass
getByTestId('add-to-cart').or(getByTestId('basket-add'))PassPass

Result: 21 of 21 passed on the normal shop; 4 of 9 passed after the rename. Each failure was a 3-second timeout with the message waiting for locator(...). Same result on every run (5 runs, 23 to 24 November 2026).

Playwright HTML report: 30 tests, 25 passed, 5 failed; the five failures are the exact locators on the renamed shop
Playwright’s own HTML report from our re-run on 24 November 2026: 30 tests, 25 passed, 5 failed. All five failures are the exact locators on the renamed shop.

What the result really means

  • The rename broke every “exact” locator, including the recommended ones. This rename changed text, id and test id at once. No exact locator survives that, and that is fine: a test that fails when the button’s label changes is telling you something a user would notice.
  • The survivors are not magic. The regex and or() only passed because we wrote them knowing the new name. The class locator survived because the refactor kept the class. “Any button in the card” survived because the card has one button; add a “Save for later” button and it fails with a strict mode error.
  • Scoping did the real work. All the survivors were scoped to the product card with filter({ hasText }). A short locator inside a well-chosen container is easier to keep correct than a long one from the page root.
  • Test ids are a contract, not a guarantee. getByTestId() is only stable if your team agrees not to rename test ids. Our switch broke that contract on purpose.

Five tricky cases, tested

1. Strict mode: one locator, 11 buttons

const all = page.getByRole('button', { name: 'Add to cart' });
await expect(all).toHaveCount(11);
await all.click(); // throws: strict mode violation

Fix it by scoping (filter({ hasText: 'Wireless mouse' })), not with .first(). .first() silently clicks whatever is first today, which changes when the sort order changes.

2. Iframes

A page-level locator did not find the “Join” button inside our iframe (count 0). Step into the frame first, then use normal locators:

const frame = page.getByTitle('Newsletter form').contentFrame();
await frame.getByLabel('Newsletter email (inside iframe)').fill('me@example.test');
await frame.getByRole('button', { name: 'Join' }).click();

3. Shadow DOM

The “Like” button on our test lab lives in an open shadow root. getByRole() and CSS found it; XPath found nothing (count 0). This matches the docs: “Locating by XPath does not pierce shadow roots.” Closed shadow roots are not supported at all (not tested by us).

4. Ids that change on every load

The “Save settings” button gets a random id on each load. We read the id, reloaded, and got a different one. getByRole('button', { name: 'Save settings' }) worked both times. If your app generates ids, never put them in a locator.

5. An element that appears late

await page.getByRole('button', { name: 'Load message' }).click();
await page.getByTestId('late-message').textContent();          // 'Loading…' (no waiting)
await expect(page.getByTestId('late-message')).toHaveText('Hello from the server!'); // waits

Locator actions and expect(...) assertions wait; methods that only read a value, like textContent(), return what is there right now. Reading a value instead of asserting it is a common cause of flaky tests.

Filtering and chaining

  • filter({ hasText }): the product card that contains “Wireless mouse”.
  • filter({ has }): the card that contains a “Sold out” button. In our shop, that found exactly one card, “Compact keyboard”.
  • Rows and cells: page.getByRole('row').filter({ hasText: 'Bilal' }).getByRole('cell').nth(1) read “95” from our sortable table.
  • Dialogs: page.getByRole('dialog', { name: 'Delete this item?' }).getByRole('button', { name: 'Yes, continue' }).
  • or() matches either locator; and() requires both. If both sides of or() match, strict mode still applies.

The locator order we use

  1. getByRole() with the accessible name, scoped to a container.
  2. getByLabel() for form fields.
  3. getByTestId() where text is dynamic or translated, with a team rule that test ids are not renamed casually.
  4. getByText() for checking messages, not for clicking.
  5. CSS only for things with no role, label or test id. XPath almost never: it is long, breaks on layout changes and does not see shadow DOM.

If your attribute is not data-testid, set testIdAttribute in playwright.config (for example 'data-qa').

Practise on our demo shop

Everything here runs on our free AITG Demo Shop. Turn on ?rename=1 to break your own locators, or open the test lab for the iframe, shadow DOM and changing-id cases. Switches are explained on the shop’s home page.

Get the code: all 21 tests (9 locator styles, 12 lab cases) are in our Playwright locators kit on GitHub. We ran it against a local copy of the demo shop files; the kit points at the live demo shop by default, and a BASE_URL variable switches it to a local copy.

Comparing frameworks? See Selenium vs Playwright and Cypress vs Playwright. Preparing for interviews? Locators come up in almost every round of our Playwright interview questions.

If you are moving from Selenium, our Selenium alternatives page compares the main options on the same demo shop.

FAQ

What is the best locator in Playwright?

getByRole() with an accessible name, scoped to the part of the page you mean. Playwright’s own docs recommend it first. Use getByTestId() where visible text changes often.

Is XPath bad in Playwright?

It works, but Playwright’s docs say CSS and XPath “are not recommended as the DOM can often change”. In our test, XPath also could not see a button inside shadow DOM.

What is a strict mode violation?

Playwright throws it when an action’s locator matches more than one element. Our getByRole('button', { name: 'Add to cart' }) matched 11 buttons. Narrow the locator with a container or filter().

Do Playwright locators work inside iframes?

Not from the page directly. Get the frame first, for example page.getByTitle('Newsletter form').contentFrame(), then use normal locators.

What is the difference between a locator and a selector?

A selector is the string (CSS, XPath, text). A locator is Playwright’s object that holds the selector, finds the element again on every action, waits for it and enforces strictness.

Was this helpful?Suggest an edit
Zain Ul Rehman
Zain Ul Rehman

QA Automation Engineer, Founder of AI Testing Guide. Each guide says what I ran myself and what I only researched, and I update it when things change. About me

Get new hands-on tests by email

A short email when we publish a new hands-on test, plus our free LLM attack test set. No spam.

Free. Confirm by email, unsubscribe in one click. Privacy

Scroll to Top