Back to All Questions
Question 21 of 100
Locators
Beginner
What is the importance of getByText locator in Playwright?
The Answer
`getByText` locates elements by their visible text content. It is best used for non-interactive elements like headings, paragraphs, and labels where you need to assert text is visible on the page.
Deep Dive Explanation
Unlike getByRole, getByText does NOT filter out hidden elements by default. If multiple elements share the same text, you may get a strict mode violation. Prefer getByRole for interactive elements (buttons, links) and reserve getByText for asserting paragraph content or non-interactive labels.
example.spec.ts
// Exact match
await expect(page.getByText('Welcome back!')).toBeVisible();
// Partial match (default)
await page.getByText('Sign in').click();
// Case-insensitive
await page.getByText('submit', { exact: false }).click();