Playwright Filter Locators
Playwright Filter Locators
Filtering makes a locator match fewer elements, so it finds the exact element you want.
You need it when a locator matches several elements, like the buttons in a list.
This chapter builds on the built-in locators from the Locators chapter.
Filtering and Chaining
filter({ hasText }) keeps the elements that contain a text.
filter({ has }) keeps the elements that contain another locator.
You can also chain locators.
When you call a locator method on another locator, it only searches inside the elements of the first locator.
The first test adds three todos, and presses Enter after each one, like a user.
getByRole('listitem') finds the items of the list (the <li> elements).
Example
tests/filter.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('filter, chain and pick', async ({ page }) => {
await page.goto('https://www.w3schools.com/playwright/practice/todo.html');
const input = page.getByPlaceholder('What needs to be done?');
for (const text of ['Buy milk', 'Walk the dog', 'Buy bread']) {
await input.fill(text);
await input.press('Enter');
}
const items = page.getByRole('listitem');
await expect(items).toHaveCount(3);
// Filter by text, then chain to the checkbox inside
await items.filter({ hasText: 'Walk the dog' }).getByRole('checkbox').check();
// Filter by a child element
const doneItems = items.filter({ has: page.getByRole('checkbox', { checked: true }) });
await expect(doneItems).toHaveCount(1);
await expect(doneItems).toContainText('Walk the dog');
// First, last and nth
await expect(items.first()).toContainText('Buy milk');
await expect(items.last()).toContainText('Buy bread');
await expect(items.nth(1)).toContainText('Walk the dog');
});
test('chain locators in the shop', async ({ page }) => {
await page.goto('https://www.w3schools.com/playwright/practice/shop.html');
const webcam = page.getByTestId('product').filter({ hasText: 'Webcam' });
await webcam.getByRole('button', { name: 'Add to cart' }).click();
await expect(page.getByTestId('cart-count')).toHaveText('1');
await expect(page.getByTestId('cart-total')).toHaveText('$39.90');
});
Output:
Running 2 tests using 2 workers
[1/2] [chromium] › tests/filter.spec.js:4:1 › filter, chain and pick
[2/2] [chromium] › tests/filter.spec.js:29:1 › chain locators in the shop
2 passed (1.3s)
In the shop test, every product card has an "Add to cart" button.
The filter picks the Webcam card, and the chained getByRole() finds the button inside that card only.
There are also hasNotText and hasNot, which keep the elements that do not match.
first(), last() and nth()
When a locator matches several elements, you can pick one by its position:
| Method | Picks |
|---|---|
| first() | The first matching element |
| last() | The last matching element |
| nth(index) | The element at that index. The index starts at 0, so nth(1) is the second element |
The first example in the Filtering and Chaining section uses all three on the todo list.
Use them with care: if the order of the list changes, the test picks another element.
A filter on the text is usually more reliable than a position.
Strict Mode
Locators are strict.
If an action like click() or fill() finds more than one element, Playwright stops with an error instead of guessing.
This test adds two todos, and then clicks "the" Delete button:
Example
tests/strict.spec.js
// @ts-check
import { test, expect } from '@playwright/test';
test('delete a todo', async ({ page }) => {
await page.goto('https://www.w3schools.com/playwright/practice/todo.html');
const input = page.getByPlaceholder('What needs to be done?');
await input.fill('Buy milk');
await input.press('Enter');
await input.fill('Walk the dog');
await input.press('Enter');
await page.getByRole('button', { name: 'Delete' }).click();
});
There are two Delete buttons, one for each todo, so the test fails:
Output:
Running 1 test using 1 worker
[1/1] [chromium] › tests/strict.spec.js:4:1 › delete a todo
1) [chromium] › tests/strict.spec.js:4:1 › delete a todo ─────────────────────────────────────────
Error: locator.click: Error: strict mode violation: getByRole('button', { name: 'Delete' }) resolved to 2 elements:
1) <button type="button" class="danger" aria-label="Delete Buy milk">Delete</button> aka getByRole('button', { name: 'Delete Buy milk' })
2) <button type="button" class="danger" aria-label="Delete Walk the dog">Delete</button> aka getByRole('button', { name: 'Delete Walk the dog' })
Call log:
- waiting for getByRole('button', { name: 'Delete' })
10 | await input.press('Enter');
11 |
> 12 | await page.getByRole('button', { name: 'Delete' }).click();
| ^
13 | });
14 |
at /home/user/my-project/tests/strict.spec.js:12:54
1 failed
[chromium] › tests/strict.spec.js:4:1 › delete a todo ──────────────────────────────────────────
The error lists every element the locator found, and suggests a locator for each one.
Make the locator more specific to fix it:
Example
await page.getByRole('button', { name: 'Delete Buy milk' }).click();
Or filter the list item first, and then find the button inside it:
Example
await page.getByRole('listitem').filter({ hasText: 'Buy milk' }).getByRole('button').click();
Note: Strict mode applies to actions, and to assertions about one element, like toHaveText('Buy milk').
Assertions about a list, like toHaveCount(), and methods like count() and all() work with many elements.