Playwright closest

Playwright closest method

The closest method in Playwright allows you to find the closest ancestor element that matches a given selector.

Syntax:

const elementHandle = await page.$(selector);
const closestElementHandle = await elementHandle.closest(selector);

Explanation:

The closest method is called on an ElementHandle object representing a particular element on the page. It takes a selector as an argument to specify which ancestor element we are looking for. The method returns a new ElementHandle representing the closest matching ancestor element or null if no match is found.

Example:

Let’s say we have the following HTML structure:

<div id="parent">
  <div id="child">
    <p>Hello World</p>
  </div>
</div>

To find the closest parent of the <p> element with the id “child” that has a class of “container”, we can use the following code:

const parentElementHandle = await page.$('#child');
const closestElementHandle = await parentElementHandle.closest('.container');

If there is an ancestor element with the class “container”, the closest method will return an ElementHandle representing that ancestor element. Otherwise, it will return null.

Leave a comment