To filter a locator in @playwright/test, use the filter() method with options like hasText, has, hasNot, and hasNotText. These options help you find specific elements based on criteria such as text content or presence of another element.
Use hasText to match elements containing specified text, case-insensitive and as a substring:
import { test, expect } from '@playwright/test';
test('filter locator with hasText', async ({ page }) => {
await page.goto('https://ray.run/');
const product = page.getByRole('listitem').filter({ hasText: 'Product 2' });
});
Use has with an inner locator to match elements containing an element that matches the inner locator:
import { test, expect } from '@playwright/test';
test('filter locator with has', async ({ page }) => {
await page.goto('https://ray.run/');
const rowLocator = page.locator('.row');
await rowLocator
.filter({ hasText: 'text in column 1' })
.filter({ has: page.getByRole('button', { name: 'column 2 button' }) })
.screenshot();
});
hasNot and hasNotText options match elements that do not contain specified text or an element matching an inner locator.
When using Playwright locators, prefer user-facing attributes over XPath or CSS selectors for better resilience to DOM structure changes.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.