DEV Community

Michael Weber
Michael Weber

Posted on

Advanced Playwright Locator Strategies for Messy and Complex UIs

If you are working on real-world QA automation, you know that standard locator strategies often fail. Modern enterprise web applications are frequently full of legacy systems, dynamic IDs generated on the fly, third-party widgets, and messy DOM structures that cause standard scripts to throw strict mode violations or timeout errors.

When built-in tools like Playwright Codegen can't help, you need advanced locator techniques to keep your test suites green. In this guide, we will dive into battle-tested strategies for handling complex UI elements with ease, using pure Playwright capabilities.


1. Handling Dynamic IDs via Regex in TestIDs

Many legacy or enterprise applications generate unpredictable IDs or test attributes that append random session hashes. Instead of hardcoding brittle strings, you can pass a Regular Expression (Regex) directly into Playwright's native locator methods.

Target HTML Example:
html
<input data-testid="username_login_12345_facebook_id" type="checkbox" />
<input data-testid="username_login_9876_facebook" type="checkbox" />

Advanced Playwright Solution:
javascript
// Matches any test ID that starts with 'username_login', contains 'facebook', and optionally ends with '_id'
await page.getByTestId(/^username_login.*facebook(_id)?$/).check();


2. Partial Sibling and Text-Matching Combinations

When an element has a completely randomized middle name or hash string, you can leverage CSS attribute selectors that look for specific prefixes (^=) and suffixes ($=) simultaneously.

Target HTML Example:
html
<input class="demo" name="user_7DFDCC4674D94B1_alex" onclick="UserAction(event)">

Advanced Playwright Solution:
javascript
// Finds an input where the name starts with "user" AND ends with "alex"
await page.locator('input[name^="user"][name$="alex"]').check();


3. Preventing Strict Mode Violations with Visibility Filters

One of the most common issues in complex UIs is a Strict Mode Violation β€” when your locator matches multiple elements (e.g., one element in a mobile sidebar and one in a desktop header). If you only want to interact with what the user actually sees, use the visibility filter.

javascript
// Automatically drops hidden/duplicated elements to target only the active UI piece
await page.getByRole('button', { name: "Add" }).filter({ visible: true }).click();


4. Handling Conditional UI Flows with Promise.race

Sometimes your automation scenario faces an A/B test split, different user layouts, or multi-variant modals where you don't know which element will appear first, but the underlying business step is identical. You can handle this cleanly using Promise.race.

javascript
try {
// Executes all locator actions simultaneously; whichever resolves first wins the race
await Promise.race([
page.getByTestId('ctl_personal_q_3_3').check(),
page.getByTestId('ctl_physician_q_1_0').click(),
page.locator('#primary_user_q_1_1').selectOption('1')
]);
} catch (error) {
console.warn('None of the expected conditional elements were found or interacted with.', error);
}


5. Multi-Condition Targeting with .and()

Instead of nesting long, unreadable XPath or CSS strings, Playwright provides a native logical .and() chaining method to pinpoint elements that must fulfill multiple independent semantic queries.

javascript
// Finds a button that simultaneously has the ARIA role 'button' AND holds the specific title attribute
const subscribeButton = page.getByRole('button').and(page.getByTitle('Subscribe'));
await subscribeButton.click();


Scaling Your Automation Beyond Locators

Mastering these advanced element interaction paths is what separates flaky test suites from production-ready automation frameworks. However, writing bulletproof locators is only half the battle. To truly scale your testing, you need a smart way to orchestrate them.

Advanced test management tools like testomat.io seamlessly bridge the gap between your Playwright automated scripts and manual test cases, providing full visibility over flaky tests and execution analytics.

If you want to expand your locator toolkit further, check out this comprehensive technical blueprint on playwright locators which covers complex dropdown wrappers, custom validation states, and interacting inside multi-layered nested iFrames.

What are your go-to patterns when dealing with messy DOM structures? Let’s share strategies in the comments below!

Top comments (0)