How do I select and interact with UI elements that have identical selectors in Playwright tests?


To interact with UI elements having the same selector in @playwright/test, follow these steps:

1. Use Chaining and Filtering with Locators

Narrow down your search by filtering locators based on text or another locator. For example, filter a list item by its text content and then select a button within that item using its role attribute.

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

test('example', async ({ page }) => {
  await page.goto('https://ray.run/');
  const listItem = page.locator('li').withText('Example Item');
  const button = listItem.locator('button[role="button"]');
  await button.click();

2. Prefer User-Facing Attributes

Select elements based on their role, name, label, or other attributes visible and meaningful to users. This makes your tests less likely to break if the DOM structure changes.

3. Use Playwright's Test Generator

If you're unsure which locator to use, Playwright's test generator can generate tests and pick locators for you based on role, text content, and test ID attributes.

4. Debug with Trace Viewer Tools

Use Playwright's trace viewer tools like the Actions tab and pop-out DOM snapshot for debugging. Hover over each action of your test in the Actions tab to see the locator used and the time it took to run. Click on the pop-out icon above the DOM snapshot for a better debugging experience.

By following these steps, you can effectively select and interact with UI elements that have identical selectors in your @playwright/test tests.

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.