playwright get parent element

How to get parent element of a Playwright element

If you are working with Playwright, you may find yourself in a situation where you need to access the parent element of a certain element. For example, you may want to get the parent element of a button in order to check if it is contained within a certain div. Whatever your reason may be, Playwright makes it easy to access the parent element of any given element.

Method 1: Using the ElementHandle API

The first method to get the parent element of an element in Playwright is by using the ElementHandle API. With this method, you can call the elementHandle.parent() method to get the parent element of a given element.


const playwright = require('playwright');

(async () => {
  const browser = await playwright.chromium.launch();
  const page = await browser.newPage();
  await page.goto('https://www.example.com');

  const buttonSelector = 'button#example-button';
  const buttonElement = await page.$(buttonSelector);
  const parentElement = await buttonElement.parent();

  console.log(parentElement);

  await browser.close();
})();

In the above code, we first launch the Chromium browser and navigate to an example website. We then select a button element using its CSS selector and call the parent() method on it to get its parent element. Finally, we log the parent element to the console.

Method 2: Using the Locator API

The second method to get the parent element of an element in Playwright is by using the Locator API. With this method, you can call the locator.parent() method to get the parent element of a given element.


const playwright = require('playwright');

(async () => {
  const browser = await playwright.chromium.launch();
  const page = await browser.newPage();
  await page.goto('https://www.example.com');

  const buttonSelector = 'button#example-button';
  const parentSelector = 'div#example-div';
  const parentElement = await page.locator(buttonSelector).parent(parentSelector);

  console.log(parentElement);

  await browser.close();
})();

In the above code, we first launch the Chromium browser and navigate to an example website. We then select a button element using its CSS selector and call the parent() method on its locator, passing in the CSS selector of the parent element as an argument. Finally, we log the parent element to the console.

These are the two methods you can use to get the parent element of an element in Playwright. Depending on your use case, one method may be more suitable than the other. Experiment with both methods and see which one works best for you!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe