Rayrun

How do I select specific UI elements in Playwright Test when they have the same selector?

Answer

To reference UI elements with the same selector in @playwright/test, follow these best practices:

1. Chaining and Filtering 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. Use User-Facing Attributes

Select elements based on their role, name, label, or other attributes visible to users. This makes your tests more resilient to DOM structure changes.

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

test('example', async ({ page }) => {
  await page.goto('https://ray.run/');
  const button = page.locator('button[aria-label="Example Button"]');
  await button.click();
});

3. Utilize Playwright's Selector Engines

Playwright Test provides selector engines like nth-match and visible pseudo classes, which can be combined with other selector engines like first(), nth(), and last().

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

test('example', async ({ page }) => {
  await page.goto('https://ray.run/');
  const button = page.locator('button:nth-match(2)');
  await button.click();
});

By following these practices, you can effectively reference UI elements with the same selector 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.

TwitterGitHubLinkedIn
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 [email protected].