Back to All Questions
Question 49 of 100
Locators
Advanced
How do you filter locators in Playwright?
The Answer
Use `.filter()` on a locator to narrow results based on text content, another locator presence, or a custom predicate. Filters can be chained.
Deep Dive Explanation
Filters are evaluated lazily β they don't trigger DOM queries until an action or assertion is made. This means you can build complex filter chains without performance overhead.
example.spec.ts
// Filter by text content
const adminUsers = page.getByRole('listitem').filter({ hasText: 'Admin' });
// Filter by child element presence
const rowsWithCheckbox = page.getByRole('row').filter({
has: page.getByRole('checkbox', { checked: true })
});
// Filter by NOT having text
const incompleteItems = page.getByRole('listitem').filter({
hasNot: page.getByText('β Complete')
});
// Chain filters
const activeAdmins = page
.getByRole('listitem')
.filter({ hasText: 'Admin' })
.filter({ has: page.locator('.status-active') });
await expect(activeAdmins).toHaveCount(3);