Back to All Questions
Question 20 of 100
Locators
Intermediate
What is the importance of getByRole locators in Playwright?
The Answer
`getByRole` is Playwright's top-priority locator because it targets elements the same way users and screen readers do β by their ARIA role and accessible name. It's the most resilient locator to HTML refactoring.
Deep Dive Explanation
ARIA roles are part of the W3C accessibility spec. Every HTML element has an implicit role (button β 'button', a href β 'link', input β 'textbox'). `getByRole` uses the accessibility tree (not the DOM), making it immune to class name changes, HTML restructuring, and CSS refactoring. If `getByRole` can't find your button, a screen reader user can't either β a dual benefit.
example.spec.ts
// Buttons, links, inputs by role
await page.getByRole('button', { name: 'Add to Cart' }).click();
await page.getByRole('link', { name: 'Privacy Policy' }).click();
await page.getByRole('textbox', { name: 'Search' }).fill('laptop');
await page.getByRole('checkbox', { name: 'Remember me' }).check();
await page.getByRole('combobox', { name: 'Country' }).selectOption('US');
// Headings by level
await expect(page.getByRole('heading', { level: 1 })).toHaveText('Dashboard');
// Tables
await expect(page.getByRole('columnheader', { name: 'Price' })).toBeVisible();
await page.getByRole('row', { name: /Alice/ }).getByRole('button', { name: 'Edit' }).click();
// Hidden option (filter out hidden elements - default behavior)
await page.getByRole('button', { name: 'Submit', includeHidden: false }).click();