Locating Dynamic Elements
Handle dynamic IDs and generated classes in React, Angular and Vue apps: data-testid strategy, partial matching, stable anchors, and locator patterns to avoid.
A locator that worked yesterday and fails today is usually not a Selenium problem. It is a locator that depended on something the application never promised to keep stable: a generated ID, a hashed CSS class, a position in a list. Modern front-end frameworks generate a lot of these values, and they change on every build, every render, or every session.
This lesson covers how to recognise dynamic attributes, what to anchor on instead, how to use partial matching when you have no better option, and how to get the front-end team to give you stable hooks so you rarely need the workarounds.
Recognising Dynamic Attributes
Before writing a locator, inspect the element in two different sessions (or after a rebuild) and compare. Anything that differs is off limits. Common offenders:
| Pattern | Example | Source |
|---|---|---|
| Numeric suffix IDs | input-4821, ember123, ext-gen45 | Ember, ExtJS, legacy component libraries |
| JSF/server-generated IDs | j_idt45:username, ctl00_MainContent_txtName | JSF, ASP.NET WebForms |
React useId output | :r1:, :R2ab6:, «r3» | React 18+ useId() |
| CSS Modules | Button_primary__3xYzQ | CSS Modules / Next.js |
| CSS-in-JS | css-1x2y3z, sc-bdVaJa, jss123 | Emotion, styled-components, JSS |
| Angular view encapsulation | _ngcontent-c12, _nghost-ng-c4012345 | Angular emulated encapsulation |
| Angular debug attributes | ng-reflect-model="..." | Angular dev mode only, absent in production builds |
| Tailwind utility soup | flex items-center px-4 py-2 | Stable per build, but describes looks, not meaning |
| UUIDs | a3f9c2e1-... | Anything that generates keys at runtime |
Two categories are deceptive. ng-reflect-* attributes look perfect in a local dev build and vanish in production, so tests written against them pass locally and fail in CI against a production bundle. Utility classes like Tailwind’s are stable from build to build, but they describe appearance; the next redesign changes px-4 to px-6 and your locator is gone.
The Hierarchy of Stable Anchors
Pick the first option that exists for the element:
- A dedicated test attribute:
data-testid,data-test,data-qa,data-cy. - Semantic and accessibility attributes:
name,type,aria-label,role,for/idpairs on labels,hreffor links. - Stable, human-assigned IDs:
id="checkout-button"written by a person, not a framework. - Visible text, for buttons and links whose label is part of the spec (and not translated in your test environment).
- A stable ancestor plus a short relative path: anchor on the nearest stable container, then descend.
- Partial matching on a dynamic attribute, as a last resort.
// Best: a test hook the team maintainsdriver.findElement(By.cssSelector("[data-testid='save-invoice']"));
// Good: accessible name and roledriver.findElement(By.cssSelector("button[aria-label='Save invoice']"));
// Acceptable: text that is part of the specdriver.findElement(By.xpath("//button[normalize-space()='Save invoice']"));
// Fragile: generated class from CSS Modulesdriver.findElement(By.cssSelector(".InvoiceForm_save__2kd9X"));
// Broken tomorrow: React useId outputdriver.findElement(By.id(":r7:"));# Best: a test hook the team maintainsdriver.find_element(By.CSS_SELECTOR, "[data-testid='save-invoice']")
# Good: accessible name and roledriver.find_element(By.CSS_SELECTOR, "button[aria-label='Save invoice']")
# Acceptable: text that is part of the specdriver.find_element(By.XPATH, "//button[normalize-space()='Save invoice']")
# Fragile: generated class from CSS Modulesdriver.find_element(By.CSS_SELECTOR, ".InvoiceForm_save__2kd9X")
# Broken tomorrow: React useId outputdriver.find_element(By.ID, ":r7:")// Best: a test hook the team maintainsawait driver.findElement(By.css("[data-testid='save-invoice']"));
// Good: accessible name and roleawait driver.findElement(By.css("button[aria-label='Save invoice']"));
// Acceptable: text that is part of the specawait driver.findElement(By.xpath("//button[normalize-space()='Save invoice']"));
// Fragile: generated class from CSS Modulesawait driver.findElement(By.css('.InvoiceForm_save__2kd9X'));
// Broken tomorrow: React useId outputawait driver.findElement(By.id(':r7:'));// Best: a test hook the team maintainsdriver.FindElement(By.CssSelector("[data-testid='save-invoice']"));
// Good: accessible name and roledriver.FindElement(By.CssSelector("button[aria-label='Save invoice']"));
// Acceptable: text that is part of the specdriver.FindElement(By.XPath("//button[normalize-space()='Save invoice']"));
// Fragile: generated class from CSS Modulesdriver.FindElement(By.CssSelector(".InvoiceForm_save__2kd9X"));
// Broken tomorrow: React useId outputdriver.FindElement(By.Id(":r7:"));The data-testid Strategy
The cheapest long-term fix for dynamic elements is not a clever locator. It is a short agreement with the developers.
What to ask for
- A single attribute name used across the codebase. Pick one (
data-testidis the most common because React Testing Library uses it by default) and stick to it. - Values that describe purpose, not appearance or position:
data-testid="invoice-total", notdata-testid="right-column-span-3". - Keys on repeated items:
data-testid="order-row"plusdata-order-id="1042", so you can target a specific row without positional indexes. - Hooks on components, not just leaf elements:
data-testid="address-form"on the container lets you scope searches to it.
How to make it stick
- Put it in the component library. If the shared
Buttoncomponent forwards atestIdprop todata-testid, every button in the app can have a hook for free. - Make tests the reason. Developers keep attributes that break a test when removed. A failing pipeline is better documentation than a wiki page.
- Do not strip them in production unless there is a real reason. Several build plugins can remove
data-testidfrom production bundles, which breaks any smoke tests against production. The bytes saved are negligible. - Add them yourself. On many teams, test engineers can open a pull request that only adds attributes. It is low-risk and speeds everything up.
Note: Some teams argue for testing only through accessible roles and names, the way a user would. That is a good default for interaction, and it also improves accessibility. Test IDs fill the gaps: elements with no accessible name, repeated structures, and containers. The two approaches combine well.
Partial Matching When You Have No Choice
When the only usable attribute has a stable part and a dynamic part, match the stable part. CSS gives you three attribute operators, and XPath has functions for the same job.
| Goal | CSS | XPath |
|---|---|---|
| Starts with | [id^='user-'] | //*[starts-with(@id,'user-')] |
| Ends with | [id$='-email'] | No ends-with in XPath 1.0; use substring() or CSS |
| Contains | [class*='submitButton'] | //*[contains(@class,'submitButton')] |
| Whole class token | .active | //*[contains(concat(' ',normalize-space(@class),' '),' active ')] |
| Text contains | (not supported) | //button[contains(normalize-space(),'Save')] |
// JSF: "j_idt45:email" -> the part after the colon is stabledriver.findElement(By.cssSelector("input[id$=':email']"));
// CSS Modules: "Button_primary__3xYzQ" -> the readable prefix is stable per componentdriver.findElement(By.cssSelector("button[class*='Button_primary__']"));
// Prefix-based ID with a generated suffixdriver.findElement(By.cssSelector("[id^='order-row-']"));# JSF: "j_idt45:email" -> the part after the colon is stabledriver.find_element(By.CSS_SELECTOR, "input[id$=':email']")
# CSS Modules: "Button_primary__3xYzQ" -> the readable prefix is stable per componentdriver.find_element(By.CSS_SELECTOR, "button[class*='Button_primary__']")
# Prefix-based ID with a generated suffixdriver.find_element(By.CSS_SELECTOR, "[id^='order-row-']")// JSF: "j_idt45:email" -> the part after the colon is stableawait driver.findElement(By.css("input[id$=':email']"));
// CSS Modules: "Button_primary__3xYzQ" -> the readable prefix is stable per componentawait driver.findElement(By.css("button[class*='Button_primary__']"));
// Prefix-based ID with a generated suffixawait driver.findElement(By.css("[id^='order-row-']"));// JSF: "j_idt45:email" -> the part after the colon is stabledriver.FindElement(By.CssSelector("input[id$=':email']"));
// CSS Modules: "Button_primary__3xYzQ" -> the readable prefix is stable per componentdriver.FindElement(By.CssSelector("button[class*='Button_primary__']"));
// Prefix-based ID with a generated suffixdriver.FindElement(By.CssSelector("[id^='order-row-']"));Partial matches have two failure modes. They can match too much ([class*='button'] also matches icon-button-wrapper), and they can silently move when the stable part is renamed. Always check how many elements your partial selector matches in the browser console (document.querySelectorAll("...").length) before committing it, and include enough context to make it unique.
Warning: CSS Modules prefixes like
Button_primary__are derived from the file and class names in source code. They survive rebuilds but not refactors. Treat them as a temporary measure while you get a real test hook added.
Anchoring on Stable Ancestors and Labels
Often the element you want has nothing stable, but something near it does. Find the stable thing first and navigate from it.
Scope to a container
WebElement shipping = driver.findElement(By.cssSelector("[data-testid='shipping-address']"));shipping.findElement(By.cssSelector("input[name='postcode']")).sendKeys("SW1A 1AA");
WebElement billing = driver.findElement(By.cssSelector("[data-testid='billing-address']"));billing.findElement(By.cssSelector("input[name='postcode']")).sendKeys("EC1A 1BB");shipping = driver.find_element(By.CSS_SELECTOR, "[data-testid='shipping-address']")shipping.find_element(By.CSS_SELECTOR, "input[name='postcode']").send_keys("SW1A 1AA")
billing = driver.find_element(By.CSS_SELECTOR, "[data-testid='billing-address']")billing.find_element(By.CSS_SELECTOR, "input[name='postcode']").send_keys("EC1A 1BB")const shipping = await driver.findElement(By.css("[data-testid='shipping-address']"));await shipping.findElement(By.css("input[name='postcode']")).sendKeys('SW1A 1AA');
const billing = await driver.findElement(By.css("[data-testid='billing-address']"));await billing.findElement(By.css("input[name='postcode']")).sendKeys('EC1A 1BB');var shipping = driver.FindElement(By.CssSelector("[data-testid='shipping-address']"));shipping.FindElement(By.CssSelector("input[name='postcode']")).SendKeys("SW1A 1AA");
var billing = driver.FindElement(By.CssSelector("[data-testid='billing-address']"));billing.FindElement(By.CssSelector("input[name='postcode']")).SendKeys("EC1A 1BB");The name='postcode' locator alone would be ambiguous; scoped to a container it is precise.
Navigate from a label
Form fields with generated IDs almost always have a visible label. The label text is part of the UI spec, so it is a reasonable anchor. When the label wraps the input or uses for, XPath can bridge them:
//label[normalize-space()='Email address']/following::input[1]//label[normalize-space()='Email address']//inputThe first form finds the first input after the label in document order, which works for most form layouts. If the label uses for, you can read its for attribute at runtime and then find by that ID, whatever it happens to be this session:
WebElement label = driver.findElement(By.xpath("//label[normalize-space()='Email address']"));String inputId = label.getDomAttribute("for"); // e.g. ":r3:" this sessionWebElement email = driver.findElement(By.id(inputId)); // By.id is safe with odd characterslabel = driver.find_element(By.XPATH, "//label[normalize-space()='Email address']")input_id = label.get_dom_attribute("for")email = driver.find_element(By.ID, input_id)const label = await driver.findElement(By.xpath("//label[normalize-space()='Email address']"));const inputId = await label.getAttribute('for');const email = await driver.findElement(By.id(inputId));var label = driver.FindElement(By.XPath("//label[normalize-space()='Email address']"));var inputId = label.GetDomAttribute("for");var email = driver.FindElement(By.Id(inputId));This is how you can live with React’s useId output: you never hard-code :r3:, you ask the page for it. Note that By.id handles the colons for you; building a CSS selector like #:r3: by hand would be an invalid selector unless you escape the characters.
Relative locators
Selenium 4’s relative locators (above, below, toLeftOf, toRightOf, near) find elements by visual position relative to an anchor. They are handy for elements with no attributes at all, such as an unlabelled icon button next to a known heading. They depend on layout, so responsive breakpoints can change the result. See Relative Locators.
Framework-Specific Notes
React
useIdvalues (:r1:and variants) differ between renders and between server and client in some setups. Never hard-code them.keyprops are not rendered to the DOM. If you need row keys, ask for adata-*attribute.- Controlled inputs sometimes ignore
clear(); see clearing and typing into React inputs.
Angular
_ngcontent-*and_nghost-*attributes change with the build. Ignore them.ng-reflect-*attributes exist only in dev mode. Do not use them, even if they are tempting.formcontrolname="email"is written by developers in templates and is usually stable. It is often the best attribute available on Angular forms:input[formcontrolname='email'].- Angular Material components render predictable
mat-*element names and classes (mat-select,mat-option), which are stable within a major version.
Vue
- Scoped styles add
data-v-7ba5bd90style attributes; the hash changes when the component changes. Ignore them. - Vue does not add test hooks on its own, so
data-testidconventions matter just as much.
Component libraries
MUI, Ant Design, Chakra and similar libraries generate both stable semantic classes (MuiButton-root, ant-btn-primary) and unstable hashed ones (css-1x2y3z). The semantic classes identify the type of component, not which one, so combine them with a scoping container or accessible name.
Elements That Appear, Disappear and Re-render
“Dynamic” also describes elements whose existence changes: toasts, menus, lazily loaded sections, rows that re-render after every keystroke. These are timing problems rather than locator problems:
- Wait for the element with an explicit wait instead of finding it immediately. See Explicit Waits.
- When a framework replaces DOM nodes, element references go stale. Re-find by locator rather than holding references across actions. The retry stale element recipe shows a bounded retry.
- Checking presence without an exception is covered in element exists without exception.
Patterns to Avoid
| Avoid | Why | Instead |
|---|---|---|
Absolute XPath (/html/body/div[3]/div[2]/form/input[4]) | Breaks on any layout change | Anchor on a stable attribute or container |
Positional indexes ((//button)[7]) | Breaks when an element is added | Text, role, or test ID |
| Generated IDs and hashed classes | Change per build or render | Test IDs, labels, semantic attributes |
ng-reflect-*, data-v-*, _ngcontent-* | Dev-only or build-specific | formcontrolname, test IDs |
Over-broad contains() | Matches unintended elements | Add context; verify match count |
Styling classes (.btn-blue, .mt-4) | Change with every redesign | Purpose-based attributes |
| Locators copied from DevTools “Copy XPath” | Usually positional | Write by hand from stable anchors |
| Text in a localised UI | Breaks per locale | Test IDs, or pin the test locale |
A Practical Checklist
When you meet a dynamic element:
- Reload the page twice and compare attributes. Cross off everything that changes.
- Look for a test attribute, then semantic/ARIA attributes, then a human-written ID.
- If none exist on the element, find the nearest stable ancestor or label and navigate from it.
- Use partial matching only on a clearly stable fragment, and check the match count.
- Open a ticket or pull request to add a
data-testid, and link it from a code comment next to the workaround. - Wrap the locator in a page or component object so the eventual fix is a one-line change.
Summary
- Learn to spot generated values: numeric suffixes, hashes,
useIdoutput, encapsulation attributes. - Prefer test IDs and accessible attributes; they exist because someone intends them to stay.
- Anchor on stable containers and labels, and resolve generated IDs at runtime rather than hard-coding them.
- Treat partial matching as a temporary measure, and verify it matches exactly one element.
- The best fix is organisational: agree a test-hook convention with your developers and build it into the component library.
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.