'Playwright test library - parent element for selector

please, how to get a parent element for a text selector by the Playwright E2E library.

Is better to modify the selector (it is string by something like >> //:parent) or evaluate the selector and then call the DOM element?

(The selector content is unknown)

Thank you.



Solution 1:[1]

You can call .$ to start searching from the element:

const elem = await page.$(anySelector)
const parent = await elem.$('xpath=..')

Doc: https://playwright.dev/docs/api/class-elementhandle#elementhandleselector

Solution 2:[2]

Using the new Locator you can do:

  const elementParent = await page.locator(`${childSelector} >> xpath=..`)

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

https://playwright.dev/docs/selectors#xpath-selectors

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tomas Randus
Solution 2 neil.morrison