Playwright getByRole vs CSS Selectors: Which Breaks Less?
When locating elements in Playwright E2E tests, getByRole() did not break when I changed class names, added nested elements, or swapped the order of buttons. Depending on how they were written, CSS selectors broke in one of these three changes. When I swapped the button order, one CSS selector did not raise an error on click; it pressed the wrong button. This is useful when you want to reduce how often tests break after design changes or refactoring, and need a basis for choosing a locator.
In a test environment, I prepared the original version of a sign-up form and five versions with the button area rewritten. I wrote a test that finds the "Register" button with five locator strategies and clicks it, and ran it for every combination.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and @playwright/test 1.63.0. I wrote the tests in TypeScript and ran them only on Chromium (headless). I did not test Firefox, WebKit, or Playwright in other languages such as Python. The test page was not an external site; I built it inline with page.setContent().
The page and the five locator strategies
The test target is a form with an email input and two buttons, "Register" and "Cancel" (the labels are in Japanese on the page). Clicking "Register" shows "Registered" in a paragraph with role="status" below the form. Clicking "Cancel" shows "Cancelled". The button area in the original version is as follows.
<div class="actions">
<button type="submit" class="btn btn-primary" data-testid="submit">登録する</button>
<button type="button" class="btn" data-action="cancel">キャンセル</button>
</div>
I made five versions with only this button area changed, for six versions including the original.
- Changed class names:
btn btn-primarybecameButton_root__x1a Button_primary__k9f - Wrapped the button in an element: wrapped the "Register" button in
<span class="tooltip"> - Swapped the button order: placed "Cancel" first
- Changed the button text: changed "Register" to "Submit"
- Changed button to div: changed "Register" to
<div class="btn btn-primary" data-testid="submit">and made a click event show "Registered"
I used these five ways to locate the "Register" button:
// tests/robustness.spec.ts (partial)
const locators: [string, (page: Page) => Locator][] = [
["getByRole('button', { name: '登録する' })", (p) => p.getByRole('button', { name: '登録する' })],
["getByTestId('submit')", (p) => p.getByTestId('submit')],
["locator('.btn-primary')", (p) => p.locator('.btn-primary')],
["locator('.actions > button:first-child')", (p) => p.locator('.actions > button:first-child')],
["locator('form button[type=submit]')", (p) => p.locator('form button[type=submit]')],
];
The first locates by role (button) and name (the button's text). The second locates by a data-testid attribute added for testing. The other three are CSS selectors: one by class name, one by parent-child relationship and position, and one by element name and attribute.
There are 30 tests in total, one for each combination of the six versions and five locators. Each test fills in an email address, clicks the located button, and checks whether "Registered" appears in the status area. I set actionTimeout to 2 seconds, so a missing element fails after 2 seconds. I looped over the six versions and five locators, putting the version in v and the locator name and function in label and find, to generate the tests:
test(label, async ({ page }) => {
await page.setContent(v.html);
await page.getByLabel('メールアドレス').fill('neko@example.com');
await find(page).click();
await expect(page.getByRole('status')).toHaveText('登録しました', { timeout: 1000 });
});
Results across 30 combinations
Running npx playwright test tests/robustness.spec.ts gave 23 passes and 7 failures out of 30. The results for each combination are shown in the table below.
![Table of results for six versions (rows) and five locators (columns). The getByTestId column passed in every version. getByRole fails on the text change and the change to div. .btn-primary fails on the class name change. .actions > button:first-child fails on the wrapped and div versions, and in the swapped-order version it clicked Cancel (pink). form button[type=submit] fails only on the div version](https://neko-note.org/wp-content/uploads/2026/11/playwright-getbyrole-vs-css-matrix.png)
Here is how many of the six versions each locator passed:
| Locator | Passed | Changes that broke it |
|---|---|---|
getByRole('button', { name: '登録する' }) |
4/6 | Text change, change to div |
getByTestId('submit') |
6/6 | None |
locator('.btn-primary') |
5/6 | Class name change |
locator('.actions > button:first-child') |
3/6 | Wrapped in element, swapped order, change to div |
locator('form button[type=submit]') |
5/6 | Change to div |
Looking only at the counts, getByRole() is not especially stronger than the CSS selectors. The difference lies in which changes caused the failures.
CSS selectors that broke on class, nesting, and order changes
In the version with changed class names, locator('.btn-primary') waited 2 seconds and failed.
TimeoutError: locator.click: Timeout 2000ms exceeded.
Call log:
- waiting for locator('.btn-primary')
In the version where the button was wrapped in a <span>, .actions > button:first-child failed in the same way, because it could not find the element. The child combinator > only matches direct children, so adding one element in between stops the match.
In both versions, the button's role and visible text, as users see them, are the same as in the original. getByRole('button', { name: '登録する' }) passed in both.
In the version with swapped button order, .actions > button:first-child raised no error and clicked Cancel. The test failed because it checked the result after clicking. If a test only clicks, it can pass while pressing the wrong button.
The failure in this case was not a missing element error but a mismatch in the checked text:
Error: expect(locator).toHaveText(expected) failed
Locator: getByRole('status')
Expected: "登録しました"
Received: "キャンセルしました"
Timeout: 1000ms
The official documentation section on locating by CSS or XPath also says that CSS and XPath selectors can depend on DOM structure and implementation details, and can break when the DOM changes. Long selectors chaining things like nth-child are given as examples of bad practice.
On the other hand, selectors that use the element name and attribute, such as form button[type=submit], passed for every change in class names, nesting, and order. The ones that broke relied on class names used only for styling, or on direct parent-child relationships and position (> and :first-child).
getByRole broke when what users see changed
getByRole() failed in the version with changed text and the version where the button became a div.
In the version where the text changed to "Submit", no button matched the name "Register", so the locator failed to find it. The text users see changed, so the test has to be updated too. If you do not want text changes to break tests, you can use getByTestId(). In my six versions, only getByTestId('submit') passed in every case.
In the version where the button became a div, getByRole() failed to find it. When I used Playwright's ariaSnapshot() to output the role of the button area, the original showed - button "登録する", but the div version showed - text: 登録する, meaning it was treated as plain text rather than a button. getByTestId('submit') and locator('.btn-primary') both found and clicked this div.
However, in this version, the "Register" element cannot receive focus with the Tab key. I wrote a test that enters an email address, presses Tab to check where focus moves, and then presses Enter:
// tests/keyboard.spec.ts (partial)
await page.getByLabel('メールアドレス').fill('neko@example.com');
await page.keyboard.press('Tab');
const focused = await page.evaluate(() => document.activeElement?.outerHTML);
console.log(`${name}: Tab のあとのフォーカス = ${focused}`);
await page.keyboard.press('Enter');
await expect(page.getByRole('status')).toHaveText('登録しました', { timeout: 1000 });
In the original version, Tab moved focus to Register and registration succeeded. In the div version, focus skipped Register and moved to Cancel, so Enter cancelled the form.
元の版: Tab のあとのフォーカス = <button type="submit" class="btn btn-primary" data-testid="submit">登録する</button>
✓ 1 tests/keyboard.spec.ts:6:3 › キーボードで登録する(元の版) (155ms)
buttonをdivにした: Tab のあとのフォーカス = <button type="button" class="btn" data-action="cancel">キャンセル</button>
✘ 2 tests/keyboard.spec.ts:6:3 › キーボードで登録する(buttonをdivにした) (1.1s)
The MDN explanation of the button role says that when you build a button from an element that cannot receive focus by default, such as a <div>, you need to add role="button", make it focusable with tabindex, and implement the Enter and Space key handling yourself. getByRole() failed in this version because it caught the change that the element is no longer a button for people who use the keyboard or screen readers. Tests that located the element by test ID or class name did not notice this change and passed.
What the official docs recommend
The official documentation on locating elements recommends preferring user-facing attributes such as getByRole(), and test IDs that are set up for testing, to keep tests from breaking. The section on locating by role says to prefer role-based locators because they are closest to how users and assistive technologies such as screen readers perceive the page.
The section on locating by test ID says test IDs are the most resistant to breakage because they still work when text or roles change. It also says that because test IDs are not visible to users, you should use getByRole() or similar when the role or text matters. My results matched this description. getByTestId() passed in all six versions, including the version where Register could no longer be reached with the Tab key.
getByRole() fails when user-visible text or roles change. Because it locates elements the way users do, it also catches changes like turning a button into a div, which makes the element no longer a button for keyboard users.
Lookup speed
I also compared speed. I placed a "Delete" button in each row of a 1,000-row table and measured 30 runs of finding and clicking the button in the last row, for each of two locators. The buttons have names like aria-label="商品 999 を削除" (Delete item 999).
await page.getByRole('button', { name: '商品 999 を削除' }).click();
await page.locator('#row-999 button').click();
The median of three rounds of 30 runs was as follows:
getByRole('button', { name: '商品 999 を削除' }): 30回の中央値 50.7ms(最小 39.7ms、最大 75.5ms)
locator('#row-999 button'): 30回の中央値 49.2ms(最小 32.7ms、最大 52.9ms)
getByRole('button', { name: '商品 999 を削除' }): 30回の中央値 51.4ms(最小 41.7ms、最大 86.7ms)
locator('#row-999 button'): 30回の中央値 49.9ms(最小 32.1ms、最大 56.6ms)
getByRole('button', { name: '商品 999 を削除' }): 30回の中央値 51.6ms(最小 45.3ms、最大 67.4ms)
locator('#row-999 button'): 30回の中央値 49.7ms(最小 32.5ms、最大 53.0ms)
Even with the 1,000-row table, the difference in medians was within 2 ms per operation. In this test environment, choosing getByRole() did not noticeably slow down the tests.





