Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

playwright find child element(s) within locator

I'm trying to write a function to find child(ren) element(s) within a locator something like:

async findElements(locator: Locator){
  return locator.querySelector(some/xpath/or/css);
}

However, I'm seeing the querySelector is not available in Locator. What is the equivalent of querySelector?

like image 349
Peter Huang Avatar asked Dec 17 '25 23:12

Peter Huang


2 Answers

I figured it out,

locator.locator(some/xpath/)

or

locator.locator(some_locator)

Or, if you don't already have a variable called "locator"

page.locator(parent_selector).locator(child_selector)

where parent_selector and child_selector are strings that contain selectors

https://playwright.dev/docs/api/class-locator#locator-locator

like image 97
Peter Huang Avatar answered Dec 19 '25 23:12

Peter Huang


You may use Filter by child/descendant:

Simple Example: enter image description here

await page
    .getByRole('listitem')
    .filter({ has: page.getByRole('heading', { name: 'Product 2' }) })
    .getByRole('button', { name: 'Add to cart' })
    .click();
like image 21
Vishal Aggarwal Avatar answered Dec 19 '25 23:12

Vishal Aggarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!