πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 57 of 100
Core Concepts
Intermediate

How does strict mode work in Playwright selectors?

The Answer

Strict mode means that if a locator matches MORE than one element and you try to perform a single-element action (like `.click()`), Playwright throws an error instead of silently acting on the first match.

Deep Dive Explanation

Strict mode is a FEATURE, not a bug. It prevents 'lucky' test passes where Playwright accidentally clicks the right button out of multiple matches. In Selenium, clicking the first match would silently pass even if it was the wrong element.

example.spec.ts
// If 3 buttons match this, .click() throws:
// Error: strict mode violation: locator('button.submit') resolved to 3 elements
await page.locator('button.submit').click(); // ❌ Throws if multiple match

// Fix 1: Be more specific
await page.getByRole('button', { name: 'Submit Order' }).click(); // βœ…

// Fix 2: Use .first() if order is guaranteed
await page.locator('button.submit').first().click(); // ⚠️ Use sparingly

// Fix 3: Scope to parent container
await page.locator('#checkout-form').locator('button.submit').click(); // βœ