This prompt is designed for SDETs and automation engineers who need to generate resilient, maintainable element locators for UI test automation. It produces a prioritized selector chain with fallback logic, staleness handling, and framework-specific guidance. The core job-to-be-done is translating a UI element description, a snippet of DOM, or a component specification into a production-grade locator strategy that survives DOM refactors and reduces flaky test failures caused by brittle selectors.
Prompt
Selector Strategy and Fallback Generation Prompt Template

When to Use This Prompt
Understand the ideal conditions, required inputs, and boundaries for using the selector strategy generation prompt.
Use this prompt when you have a clear target element, know which UI framework (React, Angular, Vue, etc.) and test framework (Playwright, Selenium, Cypress) you are targeting, and can provide either a DOM snippet, a component name, or a visual description of the element. The prompt assumes you are generating a locator strategy, not an entire test script. It is most effective when integrated into a test authoring workflow where the generated selector chain is reviewed by a human before being committed to a page object or test file. Do not use this prompt for generating entire test scripts, for accessibility audits, or for performance profiling of selector execution. It is also not suitable when you have no DOM context at all and are guessing at selectors from a screenshot alone.
Before using this prompt, gather the DOM snippet or component specification, identify the test framework and UI framework in use, and define your uniqueness and resilience requirements. After receiving the output, validate the generated selectors against a live DOM or a snapshot test to confirm uniqueness and stability. Avoid treating the output as a final artifact without review—selector strategies should be tested against real DOM states, including loading, error, and empty states, to ensure the fallback chain behaves as expected under all conditions.
Use Case Fit
Where this prompt works and where it does not.
Good Fit: Stable UI with Accessible Markup
Use when: The application under test uses semantic HTML, ARIA attributes, or dedicated data-testid attributes. The prompt excels at producing a prioritized chain (data-testid → aria → text → CSS → XPath) that is resilient to minor layout changes. Guardrail: Validate generated selectors against a recent DOM snapshot to confirm uniqueness before committing to the test suite.
Good Fit: Framework-Aware Anti-Pattern Detection
Use when: You need to audit an existing selector strategy for framework-specific brittleness, such as React's auto-generated class names, Angular's ng-reflect attributes, or Vue's scoped data attributes. Guardrail: Pair the prompt's output with a linting rule in your CI pipeline that flags forbidden selector patterns automatically.
Bad Fit: Canvas, WebGL, or Game UI
Avoid when: The target element is rendered inside a <canvas>, WebGL context, or a custom game engine with no DOM representation. The prompt cannot generate meaningful CSS or XPath selectors for pixel-based interfaces. Guardrail: Fall back to coordinate-based clicks or image-recognition tools, and document the coverage gap explicitly.
Bad Fit: Rapidly Changing Development Branches
Avoid when: The UI markup is in flux across multiple feature branches with no stable test identifiers. The prompt will generate selectors that rot within days. Guardrail: Gate selector generation on the presence of a data-testid contract between developers and SDETs, and treat the prompt as a scaffolding tool, not a set-and-forget solution.
Required Inputs: DOM Context and Framework Hints
Risk: Without a DOM snippet, component name, or framework hint, the model defaults to generic CSS selectors that are highly brittle. Guardrail: Always provide a representative HTML fragment, the UI framework in use (React, Angular, Vue), and any existing selector conventions as part of the [CONTEXT] placeholder.
Operational Risk: Staleness in Dynamic SPAs
Risk: Selectors that are valid at generation time may reference detached DOM nodes in single-page applications with virtual scrolling or conditional rendering. Guardrail: Every generated selector chain must be paired with an explicit wait strategy (visibility, attached, stable) and a staleness handler that falls back to the next priority selector in the chain.
Copy-Ready Prompt Template
A reusable prompt template for generating resilient, prioritized selector chains with fallback logic and staleness handling.
This template instructs the model to produce a production-grade selector strategy for a given UI element. It forces the model to think in layers—prioritizing stable, test-specific attributes over brittle structural locators—and to provide explicit fallback logic and staleness handling. Copy the block below, replace the square-bracket placeholders with your specific context, and run it against a capable model.
markdownYou are a senior SDET designing a resilient element locator strategy for a [FRAMEWORK, e.g., Playwright, Selenium, Cypress] test suite. Your goal is to produce a prioritized, maintainable selector chain that survives DOM changes and handles dynamic rendering. **Context:** - Application Under Test: [APPLICATION_NAME] - UI Component/Page: [PAGE_OR_COMPONENT_DESCRIPTION] - Element to Locate: [ELEMENT_DESCRIPTION, e.g., 'the Submit button inside the registration form'] - Current Fragile Selector (if any): [EXISTING_SELECTOR] - Framework Version: [VERSION] **Instructions:** 1. **Analyze the Element:** Based on the description, propose a prioritized list of at least three selector strategies. The order must be from most to least resilient. 2. **Prioritization Rules:** - **Tier 1 (Highest Priority):** `data-testid`, `data-cy`, `data-test`, or other dedicated test attributes. - **Tier 2:** Accessible locators like `role`, `aria-label`, `getByText`, `getByLabel`. - **Tier 3:** Semantic CSS selectors based on stable, unique IDs or classes that are not dynamically generated. - **Tier 4 (Lowest Priority):** Structural locators like complex CSS or XPath. If you must use XPath, prefer `contains()` or `text()` over fragile absolute paths. 3. **Fallback Logic:** For each strategy, write a concise code snippet in [FRAMEWORK] that implements a fallback chain. If Tier 1 fails, it should try Tier 2, and so on. Use explicit, condition-driven waits (e.g., `waitForSelector` with a timeout) instead of `sleep` or fixed delays. 4. **Staleness Handling:** Describe how the script should handle a `StaleElementReferenceException` or detached DOM node. Include a retry loop that re-queries the DOM using the same fallback chain. 5. **Anti-Patterns to Avoid:** Explicitly list any framework-specific anti-patterns you are avoiding in your solution (e.g., Playwright's `elementHandle` for long-lived references, Selenium's implicit waits mixed with explicit waits). **Output Format:** Return your response as a structured markdown document with the following sections: - **Selector Strategy Table:** A table with columns for Priority, Strategy Type, Selector Value, and Resilience Rationale. - **Implementation Script:** A single, runnable [FRAMEWORK] code block containing the fallback chain and staleness retry logic. - **Staleness Handling Explanation:** A brief paragraph explaining the retry mechanism. - **Anti-Patterns Avoided:** A bulleted list of the specific anti-patterns you avoided.
After copying the template, the most critical adaptation is the Prioritization Rules. If your application has a mature design system with reliable data-testid attributes, you can instruct the model to strictly prefer them and treat any other selector as a fallback. Conversely, if you lack test attributes, you must guide the model toward accessible locators and stable semantic selectors. The Implementation Script section is designed to be dropped directly into a test file, but you should always review the generated wait strategy to ensure timeouts align with your application's performance profile under CI conditions. For high-risk release pipelines, treat the generated selector chain as a draft and require a peer review step before merging.
Prompt Variables
Required and optional inputs for the Selector Strategy and Fallback Generation prompt. Each placeholder must be populated with concrete, testable values before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[UI_COMPONENT_DESCRIPTION] | Describes the target element's visual label, role, and surrounding context | A 'Submit' button inside a modal footer with the ID 'checkout-modal' | Must be non-empty. Should include at least one distinguishing attribute (text, role, or container). |
[FRAMEWORK] | Specifies the target automation framework for syntax and API compatibility | Playwright | Must be one of: Playwright, Selenium, Cypress. Controls method signatures and import statements. |
[PAGE_URL_OR_ROUTE] | The application URL or route where the element is expected to be rendered | Must be a valid URL or route pattern. Used to scope selector uniqueness checks and wait strategies. | |
[DOM_SNAPSHOT_OR_HTML] | A static HTML fragment or DOM snapshot showing the target element and its ancestors | Must be valid HTML. If null, the prompt will rely solely on the description and fall back to generic strategies. | |
[EXISTING_SELECTORS] | Any selectors currently in use that are known to be brittle or failing | #submitBtn (fails after React re-render) | Optional. If provided, the prompt must explain why each existing selector is fragile and avoid repeating the same anti-pattern. |
[APPLICATION_STACK] | The frontend stack used to render the component, which influences selector strategy | React 18 with CSS Modules | Must be one of the recognized stacks (React, Angular, Vue, etc.) or 'Unknown'. Controls warnings about dynamic class names and component re-renders. |
[STALENESS_SCENARIOS] | Specific conditions that cause the element to detach, re-render, or become stale | Modal closes and reopens on payment method change | Optional. If provided, the generated strategy must include explicit staleness guards and re-query logic for each scenario. |
Implementation Harness Notes
How to wire the selector strategy prompt into a test automation framework with validation, retries, and logging.
The selector strategy prompt is designed to be called programmatically from your test authoring workflow, not as a one-off chat interaction. When an SDET identifies a UI element that needs a resilient locator chain, they should invoke this prompt with the element's HTML context, the application framework in use, and any existing brittle selectors that have failed. The prompt returns a prioritized selector array that your harness can validate before committing to the test repository. This is a generation-time prompt, not a runtime prompt—it runs during test development, not during test execution. The output feeds directly into your Page Object Model or test script as the canonical locator strategy for that element.
Integration pattern: Build a thin CLI tool or IDE extension that accepts an HTML snippet and framework identifier, calls the LLM with this prompt template, and writes the validated output into a locator registry file. The harness must enforce three validation gates before accepting the generated selectors: (1) Uniqueness check—run the proposed selectors against a static DOM snapshot or live page to confirm exactly one element matches; if multiple elements match, reject and request refinement. (2) Framework anti-pattern scan—reject selectors that use framework-generated dynamic attributes (e.g., Angular's _ngcontent-*, React's data-reactid, or auto-generated CSS module hashes) unless explicitly allowed by a [FRAMEWORK_ALLOW_LIST] parameter. (3) Fallback ordering verification—confirm that the chain progresses from most-stable to least-stable selectors (data-testid → aria → text → CSS → XPath) and that each fallback is independently resolvable. Log every generation attempt with the input context, generated selectors, validation results, and the SDET who approved the final output for auditability.
Retry and escalation logic: If validation fails, the harness should automatically retry with enriched context—append the specific validation failure message to the prompt's [CONTEXT] field and re-invoke. Limit automatic retries to two attempts. If both fail, surface the element to a human SDET with the failed attempts, the DOM context, and a pre-filled ticket suggesting manual selector authoring. For high-risk application surfaces (payment flows, authentication, data deletion), require explicit human approval in the harness UI before the generated selectors can be merged, regardless of validation pass status. Model choice: Use a model with strong HTML and CSS parsing capabilities; avoid models that hallucinate DOM structures. What to avoid: Do not use this prompt at test runtime to recover from stale element exceptions—that path leads to unpredictable selector regeneration mid-execution and makes test results non-deterministic. Instead, use the prompt during development to build resilient locators upfront, and handle runtime staleness with explicit wait strategies and periodic locator health checks in CI.
Expected Output Contract
Defines the required fields, types, and validation rules for the JSON object generated by the Selector Strategy and Fallback Generation Prompt. Use this contract to parse and validate the model's output before integrating it into your test harness.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
selector_chain | Array of objects | Array must contain at least 1 and no more than 5 objects. Order must represent priority from highest to lowest. | |
selector_chain[].strategy | String enum | Must be one of: 'data-testid', 'aria-label', 'text-content', 'css-selector', 'xpath'. No other values allowed. | |
selector_chain[].value | String | Must be a non-empty string. For 'css-selector', must not start with a digit. For 'xpath', must not contain '//*[contains(@id,"...")]' anti-pattern. | |
selector_chain[].fallback_trigger | String or null | If present, must describe a specific DOM condition (e.g., 'element not attached', 'visibility hidden') that triggers fallback to the next strategy. Null is allowed only for the last item in the chain. | |
staleness_handling | Object | Must contain 'retry_count' (integer, 0-3) and 'staleness_action' (string enum: 'refetch', 'wait_and_refetch', 'fail_test'). | |
anti_pattern_warnings | Array of strings | Each string must describe a specific anti-pattern detected in the proposed selectors (e.g., 'Dynamic ID detected', 'Index-based XPath'). Array can be empty if no anti-patterns are found. | |
framework_notes | String or null | If the target framework is Playwright, Cypress, or Selenium, this field must contain a framework-specific recommendation (e.g., 'Use locator.or() for fallback chain in Playwright'). Null is allowed if no framework was specified in [TARGET_FRAMEWORK]. |
Common Failure Modes
Selector strategies fail silently in production when the DOM changes. These are the most common failure modes and how to prevent them before they reach CI.
Brittle CSS Selector Chains
What to watch: Long CSS paths tied to presentational classes or deeply nested structures break on any UI refactor. A single class rename invalidates the entire chain. Guardrail: Enforce a selector priority order in the prompt output: data-testid → aria-label → text content → CSS → XPath. Reject any generated script that defaults to a CSS path longer than 3 levels without explicit justification.
Text Content Locator Drift
What to watch: Selectors relying on exact text matches fail when copy changes, localization runs, or dynamic user-generated content appears. A button label change from 'Submit' to 'Save' breaks the entire test. Guardrail: Require the prompt to generate regex or substring fallbacks for text-based selectors. Add a validation step that flags any text selector without a declared tolerance strategy.
Stale Element Reference Exceptions
What to watch: The script captures a DOM reference, the page re-renders, and the reference becomes invalid. This is the most common flaky-test root cause in SPA-heavy applications. Guardrail: The prompt must generate explicit staleness handling: re-query the element before interaction, wrap actions in retry loops with StaleElementReferenceError catches, and prefer locator-based APIs that auto-retry.
Non-Unique Selector Collisions
What to watch: A selector matches multiple elements, but the script assumes a single match. The automation clicks the wrong instance or fails silently. Guardrail: Add an eval criterion that checks every generated selector for uniqueness claims. The prompt output must include a uniqueness_check field per selector and a fallback strategy when multiple matches are possible.
Timing-Dependent Visibility Assumptions
What to watch: The script assumes an element is visible and interactable immediately after a navigation or action, ignoring render latency, animation frames, or lazy-loaded content. Guardrail: The prompt must generate explicit wait strategies per interaction type—waitForSelector with state: 'visible', waitForResponse after mutations, and timeout rationale. Never allow bare page.click() without a preceding visibility guard.
Framework-Specific Anti-Patterns
What to watch: Generic selector logic ignores framework-specific rendering: React virtual DOM batching, Angular zone.js change detection, or shadow DOM encapsulation in Web Components. Guardrail: The prompt must accept a [FRAMEWORK] input and adjust selector strategy accordingly. For shadow DOM, require pierce selectors or shadowRoot traversal. For React, prefer data-testid over component-internal class names.
Evaluation Rubric
Criteria for evaluating the quality of a generated selector strategy and fallback chain before integrating it into a test automation framework.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Selector Uniqueness | Primary selector resolves to exactly one element in the target DOM state | Selector matches zero elements or multiple elements when one is expected | Execute |
Fallback Chain Completeness | At least 3 fallback strategies are provided in descending order of resilience | Only one selector type is provided or fallbacks are duplicates of the primary strategy | Parse the output for distinct selector types (data-testid, aria, text, CSS, XPath); verify count >= 3 |
DOM Change Resilience | Primary selector uses a dedicated test attribute (data-testid) or a stable accessibility role | Primary selector relies on auto-generated class names, dynamic IDs, or absolute XPath indices | Inspect the primary selector string; flag if it contains CSS modules hashes, |
Staleness Handling | Script includes a condition that re-queries the DOM if a | No retry or re-query logic is present; script assumes element reference remains valid indefinitely | Scan the generated script for |
Framework Anti-Pattern Avoidance | Output avoids framework-specific anti-patterns for the target tool (e.g., no | Script contains | Regex search for |
Assertion Integration | Each selector in the chain is paired with a corresponding assertion or visibility check | Selectors are defined but never used in an | Trace selector variable usage through the script; every declared selector must appear in at least one assertion or wait statement |
Priority Rationale | A comment or annotation explains why the primary selector was chosen over the fallbacks | Selector chain is presented with no justification for the ordering | Check for inline comments or docstrings adjacent to the selector chain explaining resilience or performance rationale |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add a strict JSON output schema with required fields: primarySelector, fallbackChain, stalenessStrategy, frameworkNotes. Include explicit instructions to flag anti-patterns (e.g., indexed XPath, generated CSS classes). Wire the output into a test harness that validates selector uniqueness and DOM change resilience before script generation.
json{ "outputSchema": { "primarySelector": "string", "fallbackChain": ["string"], "stalenessStrategy": "mutationObserver | pollUntil | retryWithRefresh", "frameworkAntiPatterns": ["string"] } }
Watch for
- Silent format drift when models omit
frameworkAntiPatterns - Selectors that pass uniqueness checks but break on DOM re-render
- Missing retry budget integration with the test runner

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us