# Selectors to Avoid in Playwright: A Comprehensive Guide to Robust Test Automation

---

## Executive Summary

In Playwright-based test automation, the reliability and maintainability of your test suite hinge critically on the selectors you use to identify and interact with web elements. While Playwright offers a rich set of selector strategies, not all are equally robust. Certain types of selectors—such as those based on dynamic attributes, positional indices, or generic tags—are inherently brittle and prone to causing flaky tests. This report provides an exhaustive analysis of selectors that are not recommended for use with Playwright, explains the reasons for their unreliability, and offers practical alternatives and best practices for writing stable, future-proof tests.

The following table summarizes the main selector types that are discouraged in Playwright automation, along with concise rationales:

> **Revision note.** This guide has been checked against the official Playwright documentation
> vendored in `docs/playwright/` (`locators.md`, `best-practices-js.md`, `test-typescript-js.md`).
> Where an earlier draft disagreed with it, the official guidance now wins, and the changed
> passages are marked **Corrected**. In short: `getByText`, `getByAltText` and `getByTitle` are
> recommended built-in locators in the right context; role-plus-name does not solve localization
> any better than text does; web-first assertions, not `waitForSelector` / `waitForFunction`, are
> the answer to timing; `.first()` and relative XPath are last resorts, not robust patterns; and
> `:visible` is a Playwright selector feature, not a browser pseudo-class. Several citations in
> the draft are blogs or tutorials; for anything they contradict, prefer the official docs.

---

### Table 1: Summary of Selectors Not Recommended in Playwright

| Selector Type                                      | Example(s)                                 | Why Not Recommended                                      | Robust Alternatives                          |
|----------------------------------------------------|--------------------------------------------|----------------------------------------------------------|----------------------------------------------|
| Dynamic attribute-based (auto-generated IDs/classes)| `#id_123abc`, `.css-1a2b3c`                | Values change on each build or render                    | Test IDs, roles, labels                      |
| Positional selectors (nth-child, index-based)      | `li:nth-child(3)`, `.item:nth(2)`          | Breaks with DOM reordering or dynamic lists              | Unique attributes, text, test IDs            |
| Overly generic selectors                           | `div`, `.button`, `input`                  | Match multiple elements, cause ambiguity                 | Role, label, test ID, text                   |
| Full DOM path XPath selectors                      | `/html/body/div[2]/div[1]/button`          | Fragile to any DOM structure change                      | Role, label, test ID (any XPath is a last resort)            |
| Selectors based on visual layout or CSS properties | `:nth-of-type`, `[style]`      | Styles/layouts change frequently, not user-facing        | Role, test ID, label                         |
| Text-only selectors (localization/A-B test sensitive)| `getByText('Submit')`                      | Text changes with locale, A/B tests, or copy updates     | **Corrected:** fine for non-interactive text; role+name or label for controls; test ID if copy varies               |
| Selectors tied to transient DOM states             | `.loading`, `.skeleton`                    | Elements appear/disappear rapidly, causing race conditions| Wait for stable state, test ID               |
| Chained selectors (deep parent-child chains)       | `.container > .row > .col > button`        | Breaks with layout changes or wrapper additions          | Direct semantic locator                      |
| Shadow DOM selectors (incorrect piercing/XPath)    | `xpath=//div[@id="shadow-root"]/button`    | XPath can't pierce shadow DOM, closed roots inaccessible | Playwright locators, open shadow traversal   |
| Framework-specific generated attributes            | `.css-xyz123`, `.bem__block--mod`          | Hashes or BEM variants change with builds                | Test IDs, roles                              |
| Index-based list positions                        | `.item.nth(2)`, `.list li:first()`         | List order changes, elements added/removed               | Unique attribute, text, test ID              |
| Selectors relying on dynamic ARIA attributes       | `[aria-controls="popup-123"]`              | ARIA values may be set dynamically or change on render   | Role, test ID, label                         |
| Use of `page.$` / `page.$$` instead of locators    | `page.$('button')`                         | Bypasses auto-waiting, returns stale handles            | `page.locator()`, `getByRole`, etc.          |
| Non-strict selectors matching multiple elements    | `page.locator('button')` (multiple matches)| Causes ambiguity, strict mode errors                     | Filter to unique element, use strict mode    |
| Image/alt/title selectors with missing/variable values| `getByAltText('Logo')`, `getByTitle('Close')`| **Corrected:** recommended when present; fragile only if missing or volatile                       | Test ID, role, label                         |
| CSS pseudo-class selectors (browser-variant)       | `:hover`, `:active`                        | Pseudo-classes behave differently across browsers        | Role, test ID, explicit state checks         |
| Selectors based on computed/inline styles          | `[style*="color:red"]`                     | Styles are dynamic, not user-facing                      | Test ID, role, label                         |
| Iframe selectors without frame locators            | `page.locator('iframe').locator('button')` | Fails if frame not loaded, context not switched properly | `frameLocator()`, wait for frame             |

---

Each of these discouraged selector types is explored in detail in the following sections, with explanations, real-world examples, and robust alternatives. The report concludes with actionable strategies for stabilizing selectors, validation and maintenance practices, and tools to support robust Playwright test development.

---

## 1. Introduction: The Importance of Selector Quality in Playwright

Selector quality is the cornerstone of reliable Playwright automation. In modern web applications, UI components are frequently re-rendered, layouts shift responsively, and frameworks like React, Angular, and Vue dynamically update the DOM. Selectors that are tightly coupled to the DOM structure, styling, or transient states are highly susceptible to breaking with even minor UI changes. This leads to **flaky tests**—tests that fail intermittently for reasons unrelated to actual application defects, eroding trust in the test suite and increasing maintenance costs  [1](https://www.techlistic.com/2026/02/playwright-locators-explained-best.html)  [2](https://playwright.dev/docs/best-practices)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

Playwright’s philosophy is to encourage selectors that reflect **user-visible behavior** rather than implementation details. The most robust selectors are those that are stable across UI refactors, device breakpoints, and localization changes. This report systematically identifies selector patterns that undermine this stability and provides guidance for writing selectors that are resilient, maintainable, and aligned with best practices.

---

## 2. Dynamic Attribute-Based Selectors

### 2.1 What Are Dynamic Attribute-Based Selectors?

Dynamic attribute-based selectors target elements using attributes whose values are generated at runtime or during the build process. Common examples include auto-generated IDs (`#id_123abc`), hashed class names from CSS-in-JS libraries (`.css-1a2b3c`), or framework-generated attributes.

#### Example:

```javascript
// Fragile: ID changes on each render
await page.locator('#id_123abc').click();

// Fragile: Hashed class changes with each build
await page.locator('.css-1a2b3c').click();
```

### 2.2 Why Are They Discouraged?

- **Volatility**: These attributes are not stable; they change with every deployment, build, or even UI re-render.
- **Coupling to Implementation**: Ties tests to internal implementation details rather than user-facing behavior.
- **Maintenance Overhead**: Any change in the build process or styling pipeline can break all selectors using these attributes, leading to widespread test failures  [1](https://www.techlistic.com/2026/02/playwright-locators-explained-best.html).

### 2.3 Robust Alternatives

- **Test IDs**: Use stable, purpose-built attributes such as `data-testid`, `data-qa`, or similar.
- **Role-Based Selectors**: Use ARIA roles and accessible names.
- **Labels**: For form controls, use associated labels.

#### Example:

```javascript
// Robust: Test ID is stable and intentional
await page.getByTestId('order-submit').click();

// Robust: Role and accessible name
await page.getByRole('button', { name: 'Submit' }).click();
```

---

## 3. Positional Selectors (nth-child, Index-Based, etc.)

### 3.1 What Are Positional Selectors?

Positional selectors identify elements based on their order in the DOM, such as `nth-child`, `first-child`, or index-based XPath.

#### Example:

```javascript
// Fragile: Breaks if list order changes
await page.locator('li:nth-child(3)').click();
await page.locator('//div[@class="results"]/div[3]').click();
```

### 3.2 Why Are They Discouraged?

- **Order Sensitivity**: Any addition, removal, or reordering of elements in the list breaks the selector.
- **Dynamic Content**: Lists are often generated dynamically, making positions unreliable.
- **Ambiguity**: Index-based selectors do not convey intent and are hard to maintain  [1](https://www.techlistic.com/2026/02/playwright-locators-explained-best.html)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 3.3 Robust Alternatives

- **Unique Attributes**: Use a unique `data-testid` or another stable attribute.
- **Text Content**: Use text or accessible name to identify the element.
- **Role and Filtering**: Use role-based selectors with filters.

#### Example:

```javascript
// Robust: Filter by text
await page.getByRole('listitem').filter({ hasText: 'Product 2' }).click();

// Robust: Test ID for each item
await page.getByTestId('product-123').click();
```

---

## 4. Overly Generic Selectors

### 4.1 What Are Overly Generic Selectors?

These selectors target elements by common tag names or class names that are not unique, such as `div`, `button`, or `.input`.

#### Example:

```javascript
// Fragile: Matches multiple elements
await page.locator('button').click();
await page.locator('.input').fill('test');
```

### 4.2 Why Are They Discouraged?

- **Ambiguity**: Multiple elements may match, leading to strict mode errors or unintended interactions.
- **Non-Unique**: Generic selectors do not uniquely identify the intended element.
- **Maintenance Risk**: Adding new elements of the same type can break tests  [4](https://www.tutorialpedia.org/blog/playwright-how-to-wait-for-locator-that-matches-multiple-elements-to-not-be-visible/)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 4.3 Robust Alternatives

- **Role and Name**: Use `getByRole` with a specific name.
- **Test ID**: Use a unique test ID.
- **Label**: For form elements, use `getByLabel`.

#### Example:

```javascript
// Robust: Role and accessible name
await page.getByRole('button', { name: 'Sign in' }).click();

// Robust: Test ID
await page.getByTestId('login-input').fill('user');
```

---

## 5. XPath Selectors Relying on Full DOM Paths

### 5.1 What Are Full DOM Path XPath Selectors?

These selectors use absolute XPath expressions that traverse the entire DOM hierarchy, such as `/html/body/div[2]/div[1]/button`.

#### Example:

```javascript
// Fragile: Breaks with any DOM structure change
await page.locator('/html/body/div[2]/div[1]/button').click();
```

### 5.2 Why Are They Discouraged?

- **Extreme Fragility**: Any change in the DOM structure, even unrelated to the target element, breaks the selector.
- **Hard to Read and Maintain**: Full paths are verbose and not self-explanatory.
- **Performance**: XPath evaluation can be slower, especially with complex expressions  [5](https://software-testing-tutorials-automation.com/2025/07/locator-xpath-in-playwright.html)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 5.3 Robust Alternatives

- **Semantic Locators**: Prefer role, label, or test ID selectors.
- **Corrected — any XPath is a last resort.** An earlier draft recommended relative XPath. The
  official guide says CSS and XPath "are not recommended as the DOM can often change"
  (`docs/playwright/locators.md`, *Locate by CSS or XPath*); an XPath anchored to a test id is
  just a longer `getByTestId`.

#### Example:

```javascript
// Robust: the same contract, without XPath
await page.getByTestId('submit').click();

// Robust: Role-based
await page.getByRole('button', { name: 'Submit' }).click();
```

---

## 6. Selectors Based on Visual Layout or CSS Properties

### 6.1 What Are These Selectors?

Selectors that target elements based on their layout or CSS properties, such as `:nth-of-type` or `[style*="color:red"]`.

> **Corrected.** An earlier draft listed `:visible` here. `:visible` is part of Playwright's own
> selector engine, not a browser CSS pseudo-class, so it does not vary across browsers. The
> official guide still prefers a locator that is unique on its own, and offers
> `locator.visible()` / `filter({ visible: true })` when visibility is the only difference
> (`docs/playwright/locators.md`, *Matching only visible elements*).

#### Example:

```javascript
// Fragile: Layout and styles change frequently
await page.locator('div:nth-of-type(2)').click();
await page.locator('button[style*="color:red"]').click();
```

### 6.2 Why Are They Discouraged?

- **Non-Deterministic**: Visual states and styles can change due to responsive design, theming, or user actions.
- **Not User-Facing**: Styles are not part of the user’s interaction model.
- **Implementation Coupling**: Layout and computed styles are implementation details that change with themes and breakpoints  [6](https://stackoverflow.com/questions/78301130/is-there-any-way-to-select-i-e-create-locators-by-style-value)  [7](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/Pseudo-classes).

### 6.3 Robust Alternatives

- **Role and Name**: Use role-based selectors.
- **Test ID**: Use stable attributes.
- **Explicit State Checks**: For visibility, use Playwright’s built-in assertions.

#### Example:

```javascript
// Robust: Role and name
await page.getByRole('button', { name: 'Delete' }).click();

// Robust: Test ID
await page.getByTestId('delete-button').click();
```

---

## 7. Text-Only Selectors Sensitive to Localization or A/B Testing

### 7.1 What Are These Selectors?

Selectors that rely solely on visible text, such as `getByText('Submit')`, are sensitive to changes in language, copy, or A/B test variants.

#### Example:

```javascript
// Fragile: Text changes with localization or experiments
await page.getByText('Submit').click();
```

### 7.2 Why Are They Discouraged?

- **Localization**: Text changes with language, region, or locale.
- **A/B Testing**: Copy may be updated for experiments.
- **Dynamic Content**: Text may be truncated or reformatted on different devices  [8](https://www.thegreenreport.blog/articles/localization-testing-at-scale-playwright-strategies-for-multi-language-web-apps/localization-testing-at-scale-playwright-strategies-for-multi-language-web-apps.html)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 7.3 Robust Alternatives

> **Corrected.** Text is not a locator to avoid in general. The official guide recommends
> `getByText` for non-interactive elements (`div`, `span`, `p`) and role locators for interactive
> ones (`docs/playwright/locators.md`, *Locate by text*). Swapping `getByText('Submit')` for
> `getByRole('button', { name: 'Submit' })` does **not** fix localization: the accessible name is
> usually that same visible text. When copy genuinely varies (locales, experiments), the stable
> contract is a test id, or a test that is itself locale-aware.

- **Role and Name**: For interactive elements, use role-based selectors with accessible name.
- **Text**: For non-interactive content, `getByText`, with `{ exact: true }` or a regex to control matching.
- **Test ID**: When copy varies by locale or experiment.
- **Label**: For form controls, use associated labels.

#### Example:

```javascript
// Robust: Role and accessible name (with regex for flexibility)
await page.getByRole('button', { name: /submit/i }).click();

// Robust: Test ID
await page.getByTestId('submit-btn').click();
```

---

## 8. Selectors Dependent on Timing or Transient DOM States

### 8.1 What Are These Selectors?

Selectors that target elements present only during loading, animation, or other transient states, such as `.loading`, `.skeleton`, or elements that appear/disappear rapidly.

#### Example:

```javascript
// Fragile: Element may not be present when test runs
await page.locator('.loading').waitFor({ state: 'hidden' });
```

### 8.2 Why Are They Discouraged?

- **Race Conditions**: Tests may interact with elements before or after they are present.
- **Stale References**: Elements may be replaced or removed during re-renders.
- **Flakiness**: Timing issues lead to intermittent failures  [9](https://playwright.dev/docs/actionability).

### 8.3 Robust Alternatives

- **Wait for Stable State** (**Corrected**): Use a web-first assertion on the final, stable element, e.g. `await expect(locator).toBeVisible()`, rather than an explicit wait.
- **Test ID**: Target elements that indicate readiness.
- **Auto-Waiting**: Leverage Playwright’s auto-waiting and assertions.

#### Example:

```javascript
// Robust (Corrected): a web-first assertion waits for the stable state, and the target is
// unique on its own. The earlier `.first()` is what section 12 warns against.
await expect(page.getByTestId('results-loaded')).toBeVisible();
await page.getByTestId('product-card-123').click();
```

---

## 9. Chained Selectors That Increase Coupling to Parent Structure

### 9.1 What Are Chained Selectors?

Selectors that chain multiple parent-child relationships, such as `.container > .row > .col > button`, are tightly coupled to the DOM hierarchy.

#### Example:

```javascript
// Fragile: Any change in parent structure breaks the selector
await page.locator('.container > .row > .col > button').click();
```

### 9.2 Why Are They Discouraged?

- **Layout Sensitivity**: Adding or removing wrapper elements breaks the chain.
- **Component Refactoring**: UI libraries often introduce new containers or wrappers.
- **Maintenance Burden**: Deep chains are hard to read and update  [1](https://www.techlistic.com/2026/02/playwright-locators-explained-best.html)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 9.3 Robust Alternatives

- **Direct Semantic Locator**: Target the element directly using a unique attribute or role.
- **Test ID**: Use a stable test ID on the target element.

#### Example:

```javascript
// Robust: Direct test ID
await page.getByTestId('checkout-submit').click();

// Robust: Role and name
await page.getByRole('button', { name: 'Checkout' }).click();
```

---

## 10. Selectors That Pierce or Incorrectly Handle Shadow DOM

### 10.1 What Are These Selectors?

Selectors that attempt to traverse Shadow DOM boundaries using XPath or unsupported CSS, or that do not account for open/closed shadow roots.

#### Example:

```javascript
// Fragile: XPath cannot pierce shadow DOM
await page.locator('xpath=//div[@id="shadow-root"]/button').click();
```

### 10.2 Why Are They Discouraged?

- **Shadow DOM Encapsulation**: Standard selectors cannot access elements inside closed shadow roots.
- **XPath Limitation**: XPath does not pierce shadow DOM at all.
- **Browser Differences**: Shadow DOM behavior varies across browsers  [10](https://www.testingmavens.com/blogs/interacting-with-shadow-dom-the).

### 10.3 Robust Alternatives

- **Playwright Locators**: Use Playwright’s built-in support for open shadow DOM traversal.
- **Component APIs**: For closed shadow roots, interact via component APIs or simulate user actions.

#### Example:

```javascript
// Robust: Playwright locator traverses open shadow DOM
const close = page.locator('my-modal').getByRole('button', { name: 'Close' });
await close.click();
```

---

## 11. Selectors Using Framework-Specific Generated Attributes

### 11.1 What Are These Selectors?

Selectors that target classes or attributes generated by frameworks (e.g., CSS-in-JS hashes, BEM variants).

#### Example:

```javascript
// Fragile: Hash changes with each build
await page.locator('.css-xyz123').click();

// Fragile: BEM variant may change
await page.locator('.block__element--modifier').click();
```

### 11.2 Why Are They Discouraged?

- **Build-Time Variability**: Hashes and variants change with code or style updates.
- **Not User-Facing**: These attributes are not intended for automation.
- **High Maintenance**: Any refactor or style change can break selectors  [1](https://www.techlistic.com/2026/02/playwright-locators-explained-best.html).

### 11.3 Robust Alternatives

- **Test ID**: Use stable, intentional attributes.
- **Role and Name**: Use semantic selectors.

#### Example:

```javascript
// Robust: Test ID
await page.getByTestId('save-button').click();
```

---

## 12. Selectors Using Index-Based List Positions

### 12.1 What Are These Selectors?

Selectors that pick elements by their position in a list, such as `.item.nth(2)` or `.list li:first()`.

#### Example:

```javascript
// Fragile: List order may change
await page.locator('.item').nth(2).click();
```

### 12.2 Why Are They Discouraged?

- **Dynamic Lists**: Items may be added, removed, or reordered.
- **Ambiguity**: Index does not convey intent.
- **Flakiness**: Tests break with any change in list content  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 12.3 Robust Alternatives

- **Unique Attribute**: Use a unique identifier for each item.
- **Text Content**: Filter by text or other stable property.

#### Example:

```javascript
// Robust: Filter by text
await page.getByRole('listitem').filter({ hasText: 'Banana' }).click();
```

---

## 13. Selectors Relying on ARIA Attributes That Change Dynamically

### 13.1 What Are These Selectors?

Selectors that target ARIA attributes whose values are set dynamically, such as `[aria-controls="popup-123"]`.

#### Example:

```javascript
// Fragile: ARIA value may change on each render
await page.locator('[aria-controls="popup-123"]').click();
```

### 13.2 Why Are They Discouraged?

- **Dynamic Assignment**: ARIA attributes may be generated at runtime.
- **Lack of Stability**: Values may change with each interaction or render.
- **Not Intended for Automation**: ARIA is for accessibility, not for test targeting.

### 13.3 Robust Alternatives

- **Role and Name**: Use role-based selectors.
- **Test ID**: Use stable attributes.

#### Example:

```javascript
// Robust: Role and name
await page.getByRole('dialog', { name: 'Settings' }).click();
```

---

## 14. Selectors Using `page.$` / `page.$$` Instead of Locators

### 14.1 What Are These Selectors?

Selectors that use Playwright’s legacy `page.$` or `page.$$` methods to retrieve element handles.

#### Example:

```javascript
// Fragile: Returns stale element handle, no auto-waiting
const btn = await page.$('button.submit');
await btn.click();
```

### 14.2 Why Are They Discouraged?

- **No Auto-Waiting**: Element handles are resolved immediately, bypassing Playwright’s auto-waiting and retry logic.
- **Stale References**: Handles may become stale if the DOM changes.
- **Discouraged** (**Corrected**, was "deprecated and may be removed"): The official docs steer element work to locators; element handles remain only for rare low-level cases  [11](https://www.codiga.io/blog/playwright-best-practices-no-element-handle/)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 14.3 Robust Alternatives

- **Locators**: Use `page.locator()` or built-in locator methods.

#### Example:

```javascript
// Robust: Locator with auto-waiting
const btn = page.locator('button.submit');
await btn.click();
```

---

## 15. Selectors That Match Multiple Elements (Non-Strict Mode)

### 15.1 What Are These Selectors?

Selectors that are not specific enough and match multiple elements, leading to ambiguity and strict mode errors.

#### Example:

```javascript
// Fragile: Multiple matches cause strict mode error
await page.locator('button').click();
```

### 15.2 Why Are They Discouraged?

- **Ambiguity**: Playwright’s strict mode requires selectors to match exactly one element.
- **Unintended Interactions**: May interact with the wrong element.
- **Flakiness**: Test behavior changes with DOM updates  [4](https://www.tutorialpedia.org/blog/playwright-how-to-wait-for-locator-that-matches-multiple-elements-to-not-be-visible/)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 15.3 Robust Alternatives

- **Filter to Unique Element**: Use filters, roles, or test IDs to ensure uniqueness.
- **Strict Mode**: Always write selectors that resolve to a single element.

#### Example:

```javascript
// Robust: Role and name ensures uniqueness
await page.getByRole('button', { name: 'Submit' }).click();
```

---

## 16. Image/Alt/Title Attribute Selectors That Change or Are Missing

### 16.1 What Are These Selectors?

Selectors that rely on `alt` or `title` attributes, which may be missing or dynamically set.

#### Example:

```javascript
// Fragile: Alt text may be missing or change
await page.getByAltText('Logo').click();
```

### 16.2 Why Are They Discouraged?

- **Missing Attributes**: Not all images or elements have meaningful alt/title attributes.
- **Dynamic Content**: Alt/title may change with localization or A/B testing.
- **Accessibility Gaps**: Not all developers implement alt/title consistently  [12](https://software-testing-tutorials-automation.com/2025/07/getbyalttext-locator-playwright.html)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 16.3 Robust Alternatives

> **Corrected.** `getByAltText` and `getByTitle` are recommended built-in locators
> (`docs/playwright/locators.md`, *Quick Guide*). Use them when the attribute exists and is
> meaningful; the risk above applies only when alt or title text is missing, generated, or
> experiment-driven.

- **Alt text / title**: When present and stable, `getByAltText` / `getByTitle`.
- **Test ID**: Use a stable test ID.
- **Role and Name**: Use role-based selectors (an `img` with alt text has role `img` and that text as its name).

#### Example:

```javascript
// Robust: Test ID
await page.getByTestId('logo-image').click();
```

---

## 17. Selectors Tied to CSS Pseudo-Classes That Vary Across Browsers

### 17.1 What Are These Selectors?

Selectors that use CSS pseudo-classes such as `:hover`, `:active`, or browser-specific pseudo-classes.

#### Example:

```javascript
// Fragile: Pseudo-class behavior varies by browser
await page.locator('button:hover').click();
```

### 17.2 Why Are They Discouraged?

- **Cross-Browser Variability**: Pseudo-class support and behavior differ between browsers.
- **Not User-Facing**: Pseudo-classes represent transient states, not persistent UI elements.
- **Unpredictability**: Tests may pass in one browser and fail in another  [7](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/Pseudo-classes)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 17.3 Robust Alternatives

- **Role and Name**: Use semantic selectors.
- **Explicit State Checks**: Use Playwright’s assertions to check for state.

#### Example:

```javascript
// Robust: Role and name
await page.getByRole('button', { name: 'Hover Me' }).hover();
```

---

## 18. Selectors That Rely on Computed Styles or Inline Styles

### 18.1 What Are These Selectors?

Selectors that target elements based on computed or inline styles, such as `[style*="color:red"]`.

#### Example:

```javascript
// Fragile: Styles are dynamic and not user-facing
await page.locator('[style*="color:red"]').click();
```

### 18.2 Why Are They Discouraged?

- **Dynamic Styling**: Styles may change with themes, user preferences, or responsive design.
- **Not Stable**: Inline styles are often set dynamically.
- **Not User-Facing**: Styles do not reflect user interaction patterns  [6](https://stackoverflow.com/questions/78301130/is-there-any-way-to-select-i-e-create-locators-by-style-value)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 18.3 Robust Alternatives

- **Test ID**: Use stable attributes.
- **Role and Name**: Use semantic selectors.

#### Example:

```javascript
// Robust: Test ID
await page.getByTestId('red-button').click();
```

---

## 19. Selectors for Elements Inside Iframes Without Proper Frame Locators

### 19.1 What Are These Selectors?

Selectors that attempt to interact with elements inside iframes without switching context or using frame locators.

#### Example:

```javascript
// Fragile: Fails if frame not loaded or context not switched
await page.locator('iframe').locator('button').click();
```

### 19.2 Why Are They Discouraged?

- **Frame Context**: Elements inside iframes require switching to the correct frame context.
- **Timing Issues**: Iframes may load asynchronously.
- **Selector Failure**: Direct selectors may not find elements inside frames  [13](https://runebook.dev/en/docs/playwright/api/class-locator/locator-content-frame)  [3](https://mastersoftwaretesting.com/automation-academy/ui-automation/playwright/playwright-locators-selectors).

### 19.3 Robust Alternatives

- **Frame Locators**: Use `frameLocator()` to target elements inside iframes.
- **Explicit Waits**: Wait for the frame and its content to load.

#### Example:

```javascript
// Robust: Use frameLocator
const frame = page.frameLocator('iframe#my-iframe');
await frame.getByRole('button', { name: 'Submit' }).click();
```

---

## 20. Additional Patterns to Avoid

- **Selectors that depend on whitespace or formatting**: Text selectors sensitive to whitespace or formatting are fragile; normalize text or use regex.
- **Selectors that rely on placeholder or temporary content**: Placeholders and skeleton screens are transient; target final, stable elements.
- **Selectors that use non-unique attributes**: Attributes like `name`, `value`, or `class` may not be unique; prefer test IDs or roles. A form field's `name` is the one worth keeping as a late fallback: it is the contract with the server, so it changes less often than markup, but check it is unique on the page.

---

## 21. Recommended Alternatives and Robust Selector Patterns

### 21.1 Role-Based Selectors

Role-based selectors (`getByRole`) are the most robust and user-centric. They leverage the accessibility tree and are resilient to DOM and style changes.

#### Example:

```javascript
await page.getByRole('button', { name: 'Sign in' }).click();
```

### 21.2 Test ID Selectors

Test IDs (`getByTestId`) are stable, intentional attributes added specifically for automation.

#### Example:

```javascript
await page.getByTestId('checkout-submit').click();
```

### 21.3 Label and Placeholder Selectors

For form controls, use `getByLabel` or `getByPlaceholder` to align with user interactions.

#### Example:

```javascript
await page.getByLabel('Email').fill('user@example.com');
await page.getByPlaceholder('Enter password').fill('secret');
```

### 21.4 Locator API and Filtering

Use Playwright’s Locator API for chaining, filtering, and composing selectors.

#### Example:

```javascript
const product = page.getByRole('listitem').filter({ hasText: 'Product 2' });
await product.getByRole('button', { name: 'Add to cart' }).click();
```

### 21.5 Recommended Order

The order the official docs imply, and the one to fall back through:

1. `getByTestId`: an explicit testing contract.
2. `getByRole` with the accessible name: how users and assistive technology perceive the page.
3. `getByLabel`: form controls.
4. `getByPlaceholder`: inputs without a label.
5. `getByAltText` / `getByTitle`: where those attributes exist.
6. `getByText`: non-interactive content.
7. `page.locator()` with CSS or XPath: last resort, anchored to a stable id, never a structural path.

---

## 22. Strategies to Stabilize Selectors

### 22.1 Use Strict Mode

Strict mode ensures selectors resolve to exactly one element, preventing ambiguity.

### 22.2 Leverage Auto-Waiting

Playwright’s auto-waiting waits for elements to be actionable before interacting, reducing timing-related flakiness  [9](https://playwright.dev/docs/actionability).

### 22.3 Web-First Assertions Instead of Explicit Waits

> **Corrected.** An earlier draft recommended `waitForSelector` / `waitForFunction`. Locators
> already auto-wait, and web-first assertions such as `await expect(locator).toBeVisible()` retry
> until the condition holds (`docs/playwright/best-practices-js.md`, *Use web first assertions*).
> Reserve `expect.poll` for conditions that are not about an element.

### 22.4 Retry Mechanisms

Configure retries in CI to mitigate transient failures, but treat flaky tests as technical debt to be addressed.

---

## 23. Selector Validation and Maintenance Practices

### 23.1 Linting and Type Checking

Use linting tools (e.g., ESLint with Playwright rules) and TypeScript type checking to catch common selector mistakes before running tests  [14](https://www.checklyhq.com/blog/playwright-type-checking-and-linting/). The official guide names two specifics: the `@typescript-eslint/no-floating-promises` rule, which catches a missing `await`, and `tsc --noEmit` in CI, because Playwright transpiles TypeScript without type-checking it (`docs/playwright/best-practices-js.md`, *Lint your tests*; `docs/playwright/test-typescript-js.md`).

### 23.2 Cross-Browser and Cross-Viewport Testing

Validate selectors across browsers and devices to uncover environment-specific issues.

### 23.3 Reusable Locator Utilities

Abstract selectors into utility modules or page objects to centralize updates and improve maintainability.

### 23.4 Continuous Integration Checks

Integrate selector validation into CI pipelines to catch failures early and ensure selectors remain robust as the application evolves.

---

## 24. Tools and Utilities to Support Robust Selectors

- **Playwright Codegen**: Generates recommended selectors based on user interactions; always refactor generated selectors to follow best practices  [2](https://playwright.dev/docs/best-practices).
- **Testing Library**: Encourages user-centric selectors and can be integrated with Playwright.
- **Custom Test ID Utilities**: Enforce naming conventions and uniqueness for test IDs.
- **Static Analysis Tools**: Detect deprecated or discouraged selector patterns in code reviews.

---

## 25. Case Studies and Common Failure Modes

### 25.1 Real-World Flaky Selector Incidents

- **CI Failures Due to Dynamic IDs**: Tests passed locally but failed in CI after a build process changed all auto-generated IDs.
- **Broken Tests After UI Refactor**: Deeply chained selectors failed when a new wrapper was added for spacing.
- **Localization-Induced Flakiness**: Text-based selectors broke when the application was translated into new languages.
- **Shadow DOM Inaccessibility**: XPath selectors failed to find elements inside web components using Shadow DOM.

### 25.2 Lessons Learned

- **Selector stability is critical for test reliability**.
- **User-facing attributes and explicit contracts (test IDs, roles) are the foundation of robust automation**.
- **Continuous validation and refactoring are necessary as the application evolves**.

---

## 26. Summary Table: All Selectors Not Recommended and Rationale

| Selector Type                                      | Example(s)                                 | Rationale                                             |
|----------------------------------------------------|--------------------------------------------|-------------------------------------------------------|
| Dynamic attribute-based (auto-generated IDs/classes)| `#id_123abc`, `.css-1a2b3c`                | Values change on each build or render                 |
| Positional selectors (nth-child, index-based)      | `li:nth-child(3)`, `.item:nth(2)`          | Breaks with DOM reordering or dynamic lists           |
| Overly generic selectors                           | `div`, `.button`, `input`                  | Match multiple elements, cause ambiguity              |
| Full DOM path XPath selectors                      | `/html/body/div[2]/div[1]/button`          | Fragile to any DOM structure change                   |
| Selectors based on visual layout or CSS properties | `:nth-of-type`, `[style]`      | Styles/layouts change frequently, not user-facing     |
| Text-only selectors (localization/A-B test sensitive)| `getByText('Submit')`                      | Text changes with locale, A/B tests, or copy updates  |
| Selectors tied to transient DOM states             | `.loading`, `.skeleton`                    | Elements appear/disappear rapidly, causing race conditions|
| Chained selectors (deep parent-child chains)       | `.container > .row > .col > button`        | Breaks with layout changes or wrapper additions       |
| Shadow DOM selectors (incorrect piercing/XPath)    | `xpath=//div[@id="shadow-root"]/button`    | XPath can't pierce shadow DOM, closed roots inaccessible|
| Framework-specific generated attributes            | `.css-xyz123`, `.bem__block--mod`          | Hashes or BEM variants change with builds             |
| Index-based list positions                        | `.item.nth(2)`, `.list li:first()`         | List order changes, elements added/removed            |
| Selectors relying on dynamic ARIA attributes       | `[aria-controls="popup-123"]`              | ARIA values may be set dynamically or change on render|
| Use of `page.$` / `page.$$` instead of locators    | `page.$('button')`                         | Bypasses auto-waiting, returns stale handles         |
| Non-strict selectors matching multiple elements    | `page.locator('button')` (multiple matches)| Causes ambiguity, strict mode errors                  |
| Image/alt/title selectors with missing/variable values| `getByAltText('Logo')`, `getByTitle('Close')`| **Corrected:** recommended when present; fragile only if missing or volatile                    |
| CSS pseudo-class selectors (browser-variant)       | `:hover`, `:active`                        | Pseudo-classes behave differently across browsers     |
| Selectors based on computed/inline styles          | `[style*="color:red"]`                     | Styles are dynamic, not user-facing                   |
| Iframe selectors without frame locators            | `page.locator('iframe').locator('button')` | Fails if frame not loaded, context not switched properly|

---

## 27. Conclusion

The stability and maintainability of Playwright test automation depend fundamentally on the selectors used to identify and interact with web elements. Selectors that are tightly coupled to dynamic attributes, DOM structure, or transient states are inherently brittle and should be avoided. Instead, robust automation is achieved by prioritizing user-facing attributes—such as roles, labels, and test IDs—leveraging Playwright’s Locator API, and validating selectors across browsers and environments.

By systematically avoiding the discouraged selector patterns outlined in this report and adopting the recommended alternatives, teams can dramatically reduce test flakiness, improve confidence in their automation suites, and ensure that tests remain reliable as applications evolve.

---

**Key Takeaway:**  
*Write selectors that reflect how users interact with your application, not how the DOM happens to be built. Favor roles, labels, and test IDs over dynamic, positional, or implementation-specific selectors. Validate and maintain selectors continuously to keep your Playwright tests robust and future-proof.*