RepoPilot

What's the recommended way to select an element by text in Playwright?

About microsoft/playwright · 2 messages · last activity 7/19/2026

Question

What's the recommended way to select an element by text in Playwright?

RepoPilot

Based on the repository data, the recommended way to select an element by text in Playwright is to use the getByRole locator with the text option.

From the README example [microsoft/playwright] in the repository_data block:

page.getByRole('link', { name: 'Get started' })

This uses getByRole to find an element by its ARIA role and then filters by the text content via the name option.

For more specific text matching after locating an element, Playwright provides the toHaveText matcher [packages/playwright/src/matchers/matchers.ts:L392-L410], which lets you assert that a locator contains specific text:

await expect(locator).toHaveText(expected);

You can also use toContainText [packages/playwright/src/matchers/matchers.ts:L207-L225] to check if an element contains text as a substring rather than an exact match.

The getByRole approach is preferred because it aligns with how users actually interact with pages (by visible text and accessible roles) rather than relying on CSS selectors or XPath, making tests more maintainable and accessible-focused.

FOLLOW_UPS:

  • How do I use getByPlaceholder or getByLabel locators?
  • What's the difference between toHaveText and toContainText?
  • Can I combine multiple locator strategies with filters?

Want to ask your own question?

Open chat for microsoft/playwright

Public Q&A. Generated by RepoPilot from the actual source of microsoft/playwright. AI answers can be incomplete or stale — verify before relying on them.