← Back to library
Playwrightselectorsintermediatev1.20+

Filter a locator by text

Narrow a matched set of elements down to only those containing specific text.

1test('clicks the "View" button only on Alice's card', async ({ page }) => {
2  await page.goto('/team');
3
4  const cards = page.locator('[data-testid="member-card"]');
5
6  // filter() narrows the matched set without leaving the locator API —
7  // far more reliable than CSS :has-text() pseudo-classes
8  const aliceCard = cards.filter({ hasText: 'Alice' });
9  await expect(aliceCard).toHaveCount(1);
10
11  await aliceCard.getByRole('button', { name: 'View profile' }).click();
12  await expect(page.getByTestId('profile-drawer')).toBeVisible();
13});
#filter#hasText#locator#narrow