Playwright Selecting Elements that Contain Other Elements

Profile picture for user arilio666

This article will cover an exciting topic on selecting elements that contain another element. This means we will be selecting a parent element containing the child element.

With the help of playwright CSS pseudocode, we will be handling this.

For example, we will be automating the ivagus site.

  • Open codegen using the command with your site name.
npx playwright codegen https://www.ivagus.com

The site is open now. Let us inspect and work on some cool stuff.

  • Let us try to fetch all of the texts from this link footer place alone.

Now how shall we do this?

  • When hovering over this part, we see that this parent contains all the texts inside.

Let us move to the console part and write our personalized locator.

div#block-gavias-vitaco-linkfooter:has(a[href='#'])
  • We can see this in the console using this pseudo locator. It has fetched the parent part of the element.
  • We simply used div and id followed by ':' and 'has' within the child element CSS locator bracket.

This is the child.

await page.goto("https://www.ivagus.com/");

const linkFooter = await page.locator("div#block-gavias-vitaco-linkfooter:has(a[href='#'])").allInnerTexts();
for await (const Texts of linkFooter){
   console.log(Texts)
}
  • Using the allInnerTexts method, we managed to get the texts of the texts present within this parent using its great-grandchild present within it.

Conclusion:

In the same way, we can select all elements which contain another element.