πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 23 of 100
Locators
Intermediate

How to interact with elements using chaining locators in Playwright?

The Answer

Playwright lets you chain locators to narrow down elements precisely. Instead of a complex CSS/XPath, you combine semantic locators to target the exact element in a specific context.

Deep Dive Explanation

Chaining makes selectors resilient and self-documenting. Each step narrows the scope, so there is no ambiguity. This is far superior to writing fragile nth-child CSS selectors or long XPath expressions.

example.spec.ts
// Find the 'Add to Cart' button only within the 'Laptop' product card
await page
  .getByRole('listitem')
  .filter({ hasText: 'Laptop Pro' })
  .getByRole('button', { name: 'Add to Cart' })
  .click();

// Scoped to a section
const nav = page.getByRole('navigation', { name: 'Main' });
await nav.getByRole('link', { name: 'Products' }).click();