Locator Logic
Elements that change between visits, and elements that are only unique when two conditions are combined.
Either one: or()
a.or(b) matches whatever either locator matches. Use it when the page shows one of two things and you can't know which in advance:
const newDialog = page.getByRole('dialog', { name: 'New email' });
const draftDialog = page.getByRole('dialog', { name: 'Restore draft?' });
await expect(newDialog.or(draftDialog)).toBeVisible();
if (await draftDialog.isVisible()) {
await draftDialog.getByRole('button', { name: 'Discard' }).click();
}or() is still strict. If both sides match at the same moment, it matches two elements and an action fails. And isVisible() doesn't wait: call it only after an assertion has waited for one of the two.
Both at once: and()
a.and(b) matches elements that both locators match. It helps when no single locator is unique:
const subscribe = page
.getByRole('button', { name: 'Subscribe' })
.and(page.getByTitle('Monthly plan'));Everything except: hasNot and hasNotText
const rows = page.getByRole('row');
rows.filter({ hasNotText: 'Archived' }); // text anywhere in the row
rows.filter({ hasNot: page.getByRole('img', { name: 'Pinned' }) }); // no such element insidehasText and hasNotText look for a substring of all the text in the element, ignoring case. A sentence that happens to contain the word counts too. When the word is a badge or a label, match that element with hasNot and an exact getByText() instead.
Only the visible copy: filter({ visible: true })
Responsive pages often render an element twice, once for each screen size, and hide one with CSS. Role locators skip hidden elements on their own. Test ids, text and CSS locators don't:
// Two elements in the DOM, one hidden: a strict mode error
await expect(page.getByTestId('user-menu')).toBeVisible();
// The one the user can see
await expect(page.getByTestId('user-menu').filter({ visible: true })).toBeVisible();1. A/B test
2. One of two outcomes
3. Inbox
- Billing Invoice #1042📎Unread
- Ada Sprint notes
- CI bot Build failed on mainUnread
- Grace Re: 3 unread invoices📎
- Linus Lunch on Friday?
- HR Holiday calendar 2027📎Unread
- Newsletter What changed this month
4. Reports
5. Responsive header
Related exercises
- Dialogs & WindowsIntermediateModals & OverlaysTest modals built into the page: native and custom, stacked, and one that interrupts you.
- Dynamic ElementsAdvancedFlaky LabMake tests that pass every time, then prove it by running them many times.
- TablesIntermediateTable ActionsEdit, delete and add rows using the controls inside them.
Read the guide: Playwright locators: a practical guide with exercises