Chains, filter, has, and, or
A target among identical elements is narrowed by content and context, not by position: chained locators, filter, and and or. A chain searches for a descendant inside the matched element, while filter({ hasText }) or filter({ has }) keeps the element itself, for example the row with the right invoice. nth and first are kept for cases where the order is the requirement.
Playwright · Locators
A table has ten rows and ten "Refund" buttons. How do you click the right one without indexes?
A test has to refund invoice INV-1042. The page has ten rows, each with a "Refund" button, and getByRole('button', { name: 'Refund' }) gives a strict mode violation. The quickest "fix" is .nth(3), but tomorrow the rows are sorted differently and the test refunds someone else's invoice. This lesson is about narrowing a locator by content and context: chaining, filter, and, or, and when positional methods are still fine.
How it works and why. Every locator method returns a new locator, so they compose. A chain a.getByRole(...) searches the inner locator only inside the elements found by the outer one. filter keeps only those elements of the outer locator that match a condition. Both are lazy, like the whole Locator: nothing runs until an action or assertion. The idea is to describe the element "like a person would": "the Refund button in the row that says INV-1042". A position ("the fourth") is a description that breaks with sorting, pagination and a new row on top.
How the search area narrows
Chaining and filter at work. The typical task: find a row by its content and act inside it.
const row = page
.getByRole('row')
.filter({ hasText: 'INV-1042' })
.filter({ has: page.getByRole('cell', { name: 'Paid' }) });
await row.getByRole('button', { name: 'Refund' }).click();
const active = page.getByRole('listitem').filter({ hasNot: page.getByText('Archive') });
const toasts = page.getByRole('alert').filter({ visible: true });
filter has five conditions: hasText / hasNotText (text inside, a string or a regex), has / hasNot (a descendant that matches another locator is or is not present) and visible. The locator inside has is resolved relative to the outer element, not from the document root.
What a chain returns and what filter returns
row.getByRole('cell', { name: 'Paid' })
A chain returns a descendant: the cell itself. Clicking "Refund" through it will not work.
row.filter({ has: cell })
Returns the row that contains such a cell. Then we look for the button inside it.
and: an extra condition on the same element. and intersects two locators and the result must match both: page.getByRole('button').and(page.getByTitle('Subscribe')) is a button that also has the title "Subscribe". It is not a descendant search.
or: one of two states. or returns elements matching either locator. It helps when the app legitimately shows one of two variants, for example a cookies dialog or the "Continue" button right away:
const consent = page.getByRole('dialog', { name: 'Cookies' });
const proceed = page.getByRole('button', { name: 'Continue' });
await expect(consent.or(proceed).first()).toBeVisible();
if (await consent.isVisible()) {
await consent.getByRole('button', { name: 'Accept' }).click();
}
await proceed.click();
If both elements are present, or matches two and an action gives a strict mode violation, which is why the example uses first() before the assertion. And isVisible() does not wait, so the if branch is safe only after an assertion that guarantees one of the states has appeared.
Positional methods. first(), last() and nth(i) are a last resort. They depend on DOM order, which changes with sorting, pagination or a new item at the start. They are justified when order is the requirement, for example "the first in the list is the newest".
| Tool | Returns | Example |
|---|---|---|
| Chain | A descendant | The Delete button in the cart |
filter({ hasText }) | The same element | The row with an invoice number |
filter({ has }) | The same element | A card with a "New" badge |
and | Match with both | A button with a given title |
or | Match with either | A dialog or a next button |
nth | By position | Order is the requirement |
Limits. A text filter matches by substring, so hasText: 'INV-10' finds both INV-1042 and INV-1099: for precision use a word-boundary regex (/\bINV-1042\b/) or filter({ has: page.getByRole('cell', { name: 'INV-1042', exact: true }) }). If the identifier is not visible in text and the structure is complex, a test id on the row (data-testid="order-row") followed by filter is more fitting. In Selenium this lookup is written in XPath (//tr[contains(.,'INV-1042')]//button), which breaks with structure, while Playwright expresses it readably.
Common mistakes.
.first()against a strict mode violation: the test clicks the wrong thing and breaks when the order changes.- Mixing up a chain and
filter({ has }): you get a descendant instead of the row. orwhere certainty is needed: it hides app instability instead of exposing it.- Finding a row by index although it has unique text.
hasTextas a plain string on similar values: it matches more than intended.
Check yourself
How does page.getByRole('row').getByRole('cell', { name: 'Paid' }) differ from page.getByRole('row').filter({ has: page.getByRole('cell', { name: 'Paid' }) })?
Answer
The first returns the "Paid" cells (descendants of rows), the second returns the rows themselves that contain such a cell. To act on a row (the "Refund" button) you need the second.
A test with consent.or(proceed).click() sometimes fails with a strict mode violation. Why?
Answer
When the dialog and the button are present together, or matches two elements and click requires one. Either handle the dialog first or check presence with first(), but do not click the union.
filter and hasText, then look for the button inside the row. I use nth only when order matters. Middle/Senior: I distinguish a chain (returns a descendant) from filter({ has }) (returns the element itself), and for an extra condition and or for two legitimate states, remembering strict mode if both match. I do not use first() as a plug: I find out why there are several elements.