Locators: Finding Elements the Right Way
You'll learn how to select elements in Playwright tests using accessible, resilient locators instead of brittle CSS selectors.
Playwright provides three primary locator methods that align with how users actually interact with your application: getByRole, getByText, and getByTestId.
Why Locators Matter
Think of locators like giving directions to a friend. You could say "the third building from the left" (fragile, breaks when things move), or "the library with the big clock tower" (descriptive, survives layout changes). Good locators work the same way.
The Three Locator Types
getByRole is your go-to choice. It finds elements by their accessible ARIA role, which means if your locator works, your app is accessible:
await page.getByRole('button', { name: 'Submit' }).click();
await page.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
getByText finds elements containing specific text content—great for headings, labels, and paragraphs:
await expect(page.getByText('Welcome back!')).toBeVisible();
getByTestId is your escape hatch when semantic locators aren't practical. Add data-testid attributes to elements you need to target:
await page.getByTestId('complex-widget-trigger').click();
Priority Order
Always prefer getByRole first (accessibility wins), then getByText (user-visible content), and only use getByTestId when the others genuinely don't fit. Avoid CSS selectors like .class-name or #id—they're implementation details that break during refactoring.
Key Takeaway: Use getByRole for accessible element selection, getByText for content matching, and getByTestId as a last resort—your tests should find elements the way users do.