How do I locate and interact with elements by their ARIA role in Playwright?


Locating and Interacting with Elements by ARIA Role

In @playwright/test, you can use the getByRole method to locate and interact with elements based on their ARIA role, ARIA attributes, and accessible name. This approach is more resilient to DOM changes compared to using CSS selectors.

Consider the following DOM structure:

<h3>Sign up</h3>
  <input type="checkbox" /> Subscribe

You can interact with each element by its implicit role using getByRole:

import { test } from '@playwright/test';

test('Interact with elements by role', async ({ page }) => {
  await page.goto('https://ray.run/');

  await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
  await page.getByRole('checkbox', { name: 'Subscribe' }).check();
  await page.getByRole('button', { name: /submit/i }).click();

This code snippet demonstrates how to:

  1. Locate the heading element with the text "Sign up" and check if it's visible.
  2. Locate the checkbox element with the text "Subscribe" and check it.
  3. Locate the button element with the text "Submit" and click it.

Using getByRole allows you to interact with elements without needing a container or specific CSS selectors. For more efficient test scripts, consider using locators that are resilient to DOM changes and generating locators with Playwright's test generator tool.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.