How do I use relative selectors to target direct child elements in a chained locator with Playwright?


To target direct child elements in a chained locator using relative selectors in @playwright/test, you can use the ">>" operator. This operator helps you specify a relative selector that matches only direct children of the previous element in the chain.

Here's an example. Suppose you have a list of items, and each item has a button to add it to the cart. To select the "Add to cart" button for "Product 2", you can use the following code:

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

test('Select direct child elements', async ({ page }) => {
  await page.goto('https://ray.run');

  const product = page.getByRole('listitem').filter({ hasText: 'Product 2' });
  await product.click('>> button', { name: 'Add to cart' });

In this code snippet, getByRole('listitem') retrieves all list items on the page. Then, the filter({ hasText: 'Product 2' }) method narrows down the list to the item containing "Product 2". Finally, the click('>> button', { name: 'Add to cart' }) method uses the ">>" operator to select and click the direct child button element of the filtered list item.

Chaining and filtering like this helps you find elements on complex pages with many nested elements. It's recommended to use user-facing attributes over XPath or CSS selectors when possible, as these locators are more resilient to changes in your DOM structure.

If you need help selecting specific elements or want Playwright's test generator tool to pick locators for you automatically, consider running the Playwright codegen command with your URL:

npx playwright codegen ray.run

This command generates tests and picks locators for you, improving the locator to uniquely identify the target element and making your tests more resilient.

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.