Locators

Locator Filter in Playwright

Locator Filter in Playwright: definition, detailed explanation, practical usage, examples, mistakes, interview notes, and practice for Playwright automation.

Definition and Brief Explanation

Definition: A locator filter narrows an existing locator by text, child locator, or visibility.

Explanation: Filters solve the common problem of repeated UI blocks. Instead of clicking the first Add button on a page, you can find the product card containing Wireless Mouse and then click Add inside that card.

Why It Matters

  • It makes tests easier to read because the locator describes the target element clearly.
  • It reduces flaky failures caused by layout changes or generated CSS classes.
  • It works with Playwright auto-waiting, so actions and assertions wait for the element state.
  • It supports maintainable Page Object Model code because selectors are meaningful.

How It Works

  1. Identify the element by user-facing meaning first: role, label, text, placeholder, alt text, or title.
  2. Confirm the locator points to the intended element and is unique when used for an action.
  3. Use filters, chaining, or test ids when the page has repeated controls.
  4. Avoid positional locators unless order is the behavior being tested.

Syntax and Examples

Example 1: Filter card by text

const card = page.locator('.product-card').filter({ hasText: 'Laptop' });
await card.getByRole('button', { name: 'Add to cart' }).click();

Explanation: Finds a card containing Laptop, then clicks Add to cart inside that card.

Example 2: Filter by child locator

await page.getByRole('listitem')
  .filter({ has: page.getByRole('heading', { name: 'SQL' }) })
  .click();

Explanation: Finds the list item containing a SQL heading.

Common Mistakes

  • Using generated CSS classes as the first option.
  • Using broad text that appears in many places.
  • Adding nth() only to silence strict mode.
  • Storing element handles instead of using locators.

Interview Notes

  1. What does Locator Filter mean in Playwright?
  2. When would you choose Locator Filter?
  3. How do you make the locator unique?
  4. What makes this locator stable or unstable?

Practice Task

Create a small Playwright example for Locator Filter. Add one positive assertion, one note about what can go wrong, and one improvement that would make the test more maintainable.