SoftwareTestPilot
Automation TestingPublished: 9 min read

Playwright Strict Mode Violation: How to Fix It

Why Playwright says "strict mode violation: resolved to N elements", how to read the error, and 6 fixes: exact names, scoping, filter, test ids, nth and count.

SoftwareTestPilot
QA Editorial Team
Share:XLinkedInWhatsApp
Playwright Strict Mode Violation: How to Fix It: Automation Testing article cover, SoftwareTestPilot.com
Playwright Strict Mode Violation: How to Fix It: Automation Testing article cover, SoftwareTestPilot.com

Short answer

Playwright locators are strict: any action that works on one element, such as click(), fill() or textContent(), fails if the locator matches two or more elements. The fix is to make the locator point at exactly one element. The Playwright locator docs describe this behaviour.

In order of preference: copy the suggested locator from the error, add exact: true, scope to a parent region, use filter(), add a data-testid, and only then fall back to first() or nth().

What the error looks like

We reproduced the error on 6 Nov 2026 with Playwright 1.59 on a small test page that has a "Save" button in the header, another "Save" button in the main form and a "Save draft" button. This is the real output (Python client, so method names use snake_case; in TypeScript you will see getByRole):

Locator.click: Error: strict mode violation: get_by_role("button", name="Save") resolved to 3 elements:
    1) <button>Save</button> aka get_by_role("banner").get_by_role("button", name="Save")
    2) <button type="button">Save</button> aka get_by_role("main").get_by_role("button", name="Save", exact=True)
    3) <button type="button">Save draft</button> aka get_by_role("button", name="Save draft")

Three things to notice:

  1. "resolved to 3 elements" tells you how many matched.
  2. Match 3 is "Save draft". Role names match as a case-insensitive substring unless you ask for an exact match.
  3. Each line ends with "aka ...", a unique locator Playwright worked out for that element. Often you can copy it as is.

Why Playwright is strict

Older tools quietly used the first match. That hides bugs: if a second "Delete" button appears above the one you meant, the test deletes the wrong record and may still pass. Strictness forces you to say which element you mean, so a changed page fails loudly instead of silently testing the wrong thing.

Strictness applies to single-element actions and to assertions like toHaveText on a single element. Methods that are meant for many elements, such as count(), all(), allTextContents() and the toHaveCount assertion, do not throw.

Six fixes, from most to least stable

1. Exact name match

// Matches "Save" and "Save draft"
await page.getByRole('button', { name: 'Save' }).click();
// Matches only buttons named exactly "Save"
await page.getByRole('button', { name: 'Save', exact: true }).click();

In our test page this cut the matches from 3 to 2, because there were still two real "Save" buttons. That is common: exact fixes substring clashes, not genuine duplicates.

2. Scope to a parent region

await page.getByRole('main')
  .getByRole('button', { name: 'Save', exact: true })
  .click();

Chaining searches inside the first locator. This click succeeded in our run. Landmarks (banner, main, navigation, dialog) or a form, card or table row make good parents.

3. Filter by text or by a child

const row = page.getByTestId('row').filter({ hasText: 'Beta' });
await expect(row).toHaveText('Beta');

// Row that contains a specific button
await page.getByRole('listitem')
  .filter({ has: page.getByRole('button', { name: 'Edit' }) })
  .click();

In our run, getByTestId('row') matched two items and threw; adding filter({ hasText: 'Beta' }) returned one. See filtering locators.

4. Add a unique test id

If you can change the app, add data-testid="header-save" and use page.getByTestId('header-save'). It is stable but invisible to users, so prefer role locators where they are already unique.

5. Position: first(), last(), nth()

await page.getByTestId('row').nth(0).click(); // zero-based
await page.getByTestId('row').first().click();

Use these only when the position is the requirement, such as "the newest order is at the top". If the order can change, the test becomes flaky. The nth() docs carry the same warning.

6. You wanted many elements: use a multi-element method

await expect(page.getByTestId('row')).toHaveCount(2);
const names = await page.getByTestId('row').allTextContents();

The TypeScript snippets above mirror the calls we ran in Python but were not themselves executed.

Which fix to use: decision table

What the error list showsCauseBest fix
Extra match has a longer name ("Save draft")Substring name matchexact: true
Same element in header and in the pageReal duplicate in different regionsScope to main, dialog etc.
Many list or table rowsLocator targets a repeated itemfilter({ hasText }) or filter({ has })
A hidden copy (mobile menu, closed modal)Hidden elements still matchScope to the visible container, or filter({ visible: true }) in recent versions
Identical elements with no differenceApp gives no unique handleAsk for a data-testid; meanwhile nth()
You meant "all of them"Wrong methodtoHaveCount, allTextContents()

Check the visible filter option against your installed version's docs before relying on it.

How to diagnose it quickly

  1. Read the numbered list in the error and find the element you actually meant.
  2. Try the "aka" locator printed for it.
  3. Run the test with npx playwright test --debug or open the Playwright Inspector and hover your locator; every match is highlighted.
  4. Print the count while you work: console.log(await locator.count()). Aim for 1.
  5. After the fix, run the test a few times (--repeat-each=5) to confirm it is stable.

Interview answer

Q: What is a strict mode violation in Playwright and how do you fix it?

Sample answer: "Playwright locators are strict, so a single-element action fails if the locator matches more than one element. It protects you from clicking the wrong thing. I read the error, which lists every match, then make the locator unique: exact name, scope to a parent region, or filter by text or a child element. I use first() or nth() only when position is the actual requirement, because it hides the duplicate otherwise."

Likely follow-ups: Does count() throw on many matches? (No.) Why not just use first()? (It can silently pick a different element when the page changes.) More questions are on our Playwright interview questions page.

Practice exercise

A page has a cookie banner with an "Accept" button and a terms dialog with an "Accept" button and an "Accept all" button. page.getByRole('button', { name: 'Accept' }) fails. Write one locator that clicks the dialog's plain "Accept".

Answer: page.getByRole('dialog').getByRole('button', { name: 'Accept', exact: true }). Scoping removes the banner button; exact removes "Accept all".

Next step

Strict mode errors are much rarer when you choose good locators from the start. Read our Playwright locator best practices, compare selector styles in XPath vs CSS vs ID, and bring a stubborn locator to the QA Community for a second pair of eyes.

Key takeaways

  1. 1Actions like click(), fill() and textContent() need exactly one matching element; two or more throws a strict mode violation.
  2. 2The error lists every match with an "aka" locator you can often copy straight into your test.
  3. 3Name matching in getByRole is substring and case-insensitive by default, so "Save" also matches "Save draft". exact: true fixes that.
  4. 4Scoping (page.getByRole('main').getByRole(...)) and filter({ hasText }) are the most stable fixes.
  5. 5first() / nth() silence the error but hide the real problem if the order can change.

Common mistakes to avoid

  • Adding .first() everywhere to make the error go away.
  • Ignoring the suggested locators that Playwright already prints in the error.
  • Forgetting that a hidden duplicate (mobile menu, closed modal) still counts as a match.
  • Switching to long CSS or XPath chains instead of scoping a role locator.
  • Using a strict action when you actually wanted to check how many items exist (use toHaveCount).

References

  1. 1
  2. 2
  3. 3
  4. 4