Back to All Questions
Question 58 of 100
Core Concepts
Intermediate
What happens if multiple elements match a locator?
The Answer
If multiple elements match and you call a single-element action (click, fill, etc.), Playwright throws a 'strict mode violation'. Methods like `.count()`, `.all()`, and `.nth()` are designed for multi-element locators.
Deep Dive Explanation
When you EXPECT multiple elements (like a list), use `.count()` and `.all()`. When you accidentally get multiple elements (strict mode violation), it's a signal to make your locator more specific. The error message even tells you how many elements matched and their details.
example.spec.ts
// Getting count of all matches
const buttonCount = await page.getByRole('button').count();
// Iterating all matches
const allLinks = await page.getByRole('link').all();
for (const link of allLinks) {
console.log(await link.textContent());
}
// Asserting all match a condition
await expect(page.getByRole('listitem')).toHaveCount(5);
// Checking text of all matches
await expect(page.getByRole('option')).toHaveText([
'Option A', 'Option B', 'Option C'
]);