Mastering Context Clicks in Playwright: Handling Repeated Elements

Intro
You may encounter repeated elements such as buttons, links, or icons when testing web applications. These are commonly found in rows of tables or on product cards on shopping websites. A classic example is an “Add to Cart” button on every product card or a “Delete” button on each table row.
You need to identify its unique context to interact with the correct element. This involves locating a nearby unique identifier (e.g., a name, product title, or ID) and narrowing it down to the specific element in the DOM hierarchy. Playwright makes handling such scenarios seamless with its powerful selectors and APIs.
Solution
The approach to performing a “context click” (i.e., identifying and interacting with a specific repeated element) involves these steps:
1. Identify the unique identifier: Locate a unique text or attribute in the relevant row or section.
2. Traverse the DOM: Using Playwright’s flexible selectors, navigate from the unique element to the target element (e.g., button).
3. Perform the action: Execute the desired action, such as clicking the button.
Example
Let’s consider an example of a table with repeated “Delete” buttons in each row. Each row has a unique name column.
const { chromium } = require('playwright');
// Launch the browser
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();
// Navigate to the page
await page.goto('https://example.com/table');
// Unique identifier for the row (e.g., a name)
const uniqueRowText = 'John Doe';
// Locate the row containing the unique text by finding the text and climb 2 levels in the DOM
const row = await page.locator(`text=${uniqueRowText}`).locator('..').locator('..');
// Within the context of this row, find a button
const deleteButton = await row.locator('button');
// Click the button
await deleteButton.click();
console.log(`Clicked the 'Delete' button for ${uniqueRowText}`);
// Close the browser
await browser.close();
In this script:
• The locator function is used to identify the unique row by its text (text=${uniqueRowText}).
• The locator('..') moves up in the DOM hierarchy to the row container.
• A second locator narrows down to the button within the row context.
• Finally, the click action is performed on the correct button.
Summary
Handling repeated elements in Playwright becomes simple with the “context click” pattern:
• Use unique identifiers to locate the specific section or row.
• Traverse the DOM to isolate the target element.
• Perform the desired action reliably.
This technique ensures your tests remain robust, scalable, and adaptable for dynamic web pages. Start integrating context clicks into your Playwright scripts today to handle even the most complex UI layouts effortlessly!