Parent Elements | Bondar Academy
Course: Playwright UI Testing with TypeScript
Module: Locators and Assertions
Instructor: Artem Bondar
Lesson Summary
In this lesson, you will learn how to locate parent elements using Playwright. This technique is particularly useful when you lack a unique locator for the desired element. By identifying the closest unique parent element, you can effectively find child elements. Key Techniques for Locating Parent Elements Use the locator method with a second argument to specify search details. Filter results by text or locator . Utilize the filter method for more complex queries. Example 1: Locating by Text To find an nb-card with specific text, use: await page.locator('nb-card', { hasText: 'using the grid' }) This returns the specific nb-card containing the text, allowing you to chain further commands to find child elements. Example 2: Using Unique Identifiers Instead of text, you can filter by a unique ID : await page.locator('nb-card', { has: page.locator('#input-email1') }) Example 3: Chaining Filters To narrow down results, you can apply multiple filters: await page.locator('nb-card').filter({ has: page.locator('nb-checkbox') }).filter({ hasText: 'Sign in' }) Using XPath As a last resort, you can use XPath to navigate one level up in the DOM: await page.locator('text=using the grid').locator('..').locator('input[type="email"]') In summary, to find web elements using Playwright, leverage the locator method with filters for text or locators, or use the filter method for chaining multiple conditions. For simple parent-child relationships, XPath can be used as a last option.