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

How do you handle multiple elements that match the same locator?

The Answer

When a locator matches multiple elements, use `.first()`, `.last()`, `.nth(n)`, `.filter()`, or add more specificity to the locator to disambiguate.

Deep Dive Explanation

`.nth()` and `.first()` are fragile β€” the order of elements can change. Always prefer `.filter({ hasText: '...' })` or scoping with a parent locator when possible, as these are resilient to DOM reordering.

example.spec.ts
const rows = page.getByRole('row');

// Index-based access
await rows.first().click();
await rows.last().getByRole('button', { name: 'Edit' }).click();
await rows.nth(2).getByRole('checkbox').check(); // 0-indexed

// Filter for specificity (PREFERRED)
await page
  .getByRole('row')
  .filter({ hasText: 'John Doe' })
  .getByRole('button', { name: 'Edit' })
  .click();

// Count elements
const count = await rows.count();
expect(count).toBe(10);

// Iterate all matching elements
for (const row of await rows.all()) {
  const text = await row.textContent();
  console.log(text);
}