Locators, and Locator vs ElementHandle
A Locator is a search recipe, not a found node: Playwright searches again on every action, so a DOM re-render does not make it stale. An ElementHandle holds one concrete node and fails once that node is replaced, which is why the documentation recommends locators. Pick locators by user-facing traits: role with name, label, text, then test id, and CSS or XPath only as a last resort.
Playwright · Locators
A designer renamed a button class and 40 tests failed. How do you write locators that survive it?
A team has 40 tests that click .btn-primary. A style refactor renames the class and the whole suite goes red while the app works fine. Another test keeps a node from page.$, and after a re-render the click goes to a dead element. Both problems share one cause: the test describes the element by its markup rather than by what the user sees. This lesson answers three questions: which locator to pick first, why a Locator is lazy, and why it replaced ElementHandle.
What a Locator is and why it is lazy. A Locator does not hold a found element. It is a search recipe: a string such as getByRole('button', { name: 'Save' }) plus a reference to the page. The search runs every time an action or an assertion is called. That is deliberate, because modern pages redraw the DOM constantly and a framework can replace a node between two lines of a test. If a locator held a concrete node, every re-render would invalidate it (in Selenium that is StaleElementReferenceException). A recipe simply finds the new node on the next action and also waits for the element to be ready (attached, visible, stable, enabled; see the actionability lesson).
const save = page.getByRole('button', { name: 'Save' }); // nothing is searched
await page.goto('/profile'); // a locator can be created before the page opens
await save.click(); // search and waiting happen here
await page.reload();
await save.click(); // the same locator finds the new node
Locator priority. Playwright recommends user-facing attributes: what the user sees and hears, not how the page is built. A practical ladder is: role with an accessible name, then label, placeholder and text, then test id, and CSS or XPath last. The higher the rung, the less the test depends on markup and the more it checks accessibility: if a button cannot be found by role and name, a screen reader will not find it either.
The locator choice ladder
| Locator | Typical use |
|---|---|
getByRole | Buttons, links, headings, checkboxes and other ARIA roles |
getByLabel | Form fields with a label |
getByText | Non-interactive text: paragraphs, messages |
getByTestId | Dynamic content, icons, multilingual UI |
Example: before and after. A test that survives redesigns looks at meaning, not at markup:
// before: tied to classes and DOM position
await page.locator('div.cart > div:nth-child(2) button.btn-primary').click();
// after: role, name and context
await page
.getByRole('region', { name: 'Cart' })
.getByRole('button', { name: 'Place order' })
.click();
await expect(page.getByText('Order created')).toBeVisible();
The second version survives a new class and a change of nesting. It fails only when something the user would notice changes: the button's name or its disappearance. That is the right kind of failure.
Strict mode. If a locator matches several elements and the action expects one (click, fill), Playwright throws instead of picking the first. This is a safeguard: the test will not click "some" button and pass by accident. The message looks like this (shortened):
Error: strict mode violation:
getByRole('button', { name: 'Delete' }) resolved to 3 elements:
1) <button class="btn">Delete</button> aka …
2) <button class="btn">Delete</button> aka …
The right reaction is to find out why there are three and narrow the locator (the next lesson). Strict mode also applies to single-element assertions such as toBeVisible, while collection methods (count, all, toHaveCount, toHaveText with an array) do not apply it.
Locator versus ElementHandle. An ElementHandle holds a reference to one concrete DOM node captured once (page.$, locator.elementHandle()). It never re-resolves the element and has no strict mode: actions on it wait for actionability of that one node only and throw once it is replaced. The Playwright docs discourage it and recommend locators; page.$ and page.$$ belong to the same discouraged group.
A recipe or a node reference
ElementHandle
Holds one concrete node. Never re-resolves, no strict mode. After a re-render the node is invalid and the action fails or misses.
Locator
Holds a search recipe and searches again on every action. Waits for the element to be ready and refuses to click a "random" one of several.
When you need custom logic over a node, locator.evaluate() is usually enough: it also resolves the element at call time.
// bad: the node is captured once
const handle = await page.$('.price');
await handle?.click();
// good: a locator and evaluate on it
const width = await page.getByTestId('banner').evaluate((el) => el.clientWidth);
Limits. Lazy search means a mistake in a locator shows up only at the moment of the action, not at creation. getByRole alone does not guarantee uniqueness: strict mode does that at action time. Roles work only when the markup is semantic: for a <div onClick> with no role it is better to fix the app than to flee to CSS. In Cypress a similar idea lives in Testing Library (findByRole); in Selenium By.cssSelector stays the main tool and a WebElement goes stale.
Common mistakes.
- Starting with CSS classes and XPath: the first redesign breaks tests while the app works.
- Storing
await page.$(...)in a variable: after a re-render the node is dead and the error appears far from the cause. - "Fixing" a strict mode violation with
.first(): the test clicks the wrong thing and breaks when the order changes. - Using
getByTextfor buttons:getByRole('button')also checks the role.
Check yourself
A locator is created before page.goto, and the first action comes after it. Is that a mistake?
Answer
No. A locator only stores a recipe and searches nothing. The search and the waiting happen at click(), on the page that is already open. So one locator can be created once and used after a reload or a re-render.
A test stores const el = await page.$('.row') and clicks el a second later. Why can the click fail while the equivalent locator does not?
Answer
Between the two lines the framework may have replaced the DOM node. The ElementHandle points at the old, removed node and does not search again. A locator searches anew on every action, so it finds the new node and waits for it to be ready.
getByRole and a name because that is how the user sees the element, then label and text, and I take a test id when there is no stable role. A Locator is lazy, so there is no stale element. Middle/Senior: A Locator stores a search recipe and re-resolves it on every action, and strict mode stops me from clicking a random element among several. I rarely use ElementHandle: it never re-resolves the node and a re-render invalidates it. I investigate a strict mode failure instead of muting it with first().