Skip to contentPlayForge

How do I find an element inside another element in Playwright?

Written by Jatin Thacker, Automation Architect · Updated

Chain locators together by invoking locator methods on an existing locator. For example, parentLocator.getByRole('button') searches strictly inside the DOM subtree of parentLocator.

This answer is one piece of Chapter 9: Locators I: What the User Sees.

  • getByRole and the Accessible Name
  • getByText, getByLabel, getByPlaceholder, getByTestId
  • Strict Mode — One Locator, One Element

Locators in Playwright can be chained to isolate searches to a specific card, table row, or dialog component. You begin by creating a locator for the outer container and then call child locator methods directly on that handle, such as card.getByRole('button') or row.getByTestId('edit').

Chaining keeps test code readable and avoids strict mode violations on repeated interface patterns. On an ecommerce page with twenty product cards that all contain an "Add to cart" button, scoping inside page.locator('article[data-sku="MRD-1003"]') guarantees Playwright only searches for the button inside that specific product's container.

Every chained locator preserves auto-waiting and lazy evaluation. Playwright re-evaluates both parent and child locators every time an action or assertion executes, so component re-renders will never leave you with stale element references.

chaining-locators.spec.js(https://practice.learnplayforge.com)
import { test, expect } from '@playwright/test'; test('chaining locators to find elements inside another', async ({ page }) => { await page.goto('/catalog.html?mock=static&seed=42&autologin=1'); const productCard = page.locator('article[data-sku="MRD-1003"]'); const addButton = productCard.getByRole('button', { name: 'Add to cart' }); await expect(addButton).toBeVisible(); });
Output
1 passed (3.1s)
Test yourself
You have a card locator const card = page.locator('article.featured'). How do you find the 'Buy' button inside that specific card?

Practised in the full course: the drill Three queues, one heading.

See the chapter

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.