How do I select multiple elements from a list using Playwright without relying on the nth method?


Selecting Multiple Elements from a List in Playwright

To select multiple elements from a list without using the nth method, you can use chaining and filtering. Locators can be chained to narrow down the search to a specific part of the page. You can filter locators by text or another locator, allowing you to select specific elements within a list.

For example, use Playwright's getByRole method to select an element based on its role attribute and filter it further based on its text content:

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

test('Select multiple elements from a list', async ({ page }) => {
  await page.goto('https://ray.run');

  const product = page.getByRole('listitem').filter({ hasText: 'Product 2' });

  // Perform actions on the selected element

This code returns an element that matches both the 'listitem' role and contains the text 'Product 2'. You can then perform actions on this element as needed.

Keep in mind that relying solely on DOM structure for selecting elements is not recommended, as it may lead to failing tests if your DOM changes. Instead, use user-facing attributes such as role or aria-label when possible.

Playwright also provides a test generator that can generate tests and pick locators for you. It prioritizes role, text, and test id locators when generating selectors, making them more resilient to changes in the DOM.

In summary, use chaining and filtering locators to select multiple elements from a list without the nth method. Additionally, prioritize user-facing attributes for more resilient selectors, and consider using Playwright's test generator tool for generating robust selectors.

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.