Playwright Get Parent Element

Profile picture for user arilio666

In this article, we will see how we can get the parent of an element.

  • Consider this table site where we can see the row tr.
  • If we can see closely, all the rows elements are within tr.
  • Which makes it parent, and with tr, we will get the row's content in two ways in this article.
  • We will take the "Phaedrum9" text as a reference for the parent tr with which the rows will be fetched.

1.) Locator With Option Has

await page.goto('https://the-internet.herokuapp.com/challenging_dom#delete');
            const wholePage = await page.locator('tr', { has: page.locator('text="Phaedrum9"') })

            const textt = await wholePage.textContent()
            
console.log(textt)    
  • Here we can see we have taken the parent of the elements within it, and with options, we took the text related to the parent.
  • This will fetch the entire row with the text "Phaedrum9".
  • Here, it has the texts of all the elements within the parent tr.

2.): Has-Text

await page.goto('https://the-internet.herokuapp.com/challenging_dom#delete');
            const row = page.locator('tr:has-text("Phaedrum9")');
            const textt = await row.textContent()
            
console.log(textt)    
  • Here we have used the CSS: has text method with the same parent with different syntax this time.
  • This will do the same thing as it has done with Has.

Conclusion:

This is how we can isolate the parent element and do operations.