Skip to main content
SeleniumDecoded
Chapter 2 · Lesson 8 of 8 Locators & Navigation
On this page

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.

Selenium 4 Stable 9 min read · Updated · Verified against Selenium 4.52.0

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:

PatternExampleSource
Numeric suffix IDsinput-4821, ember123, ext-gen45Ember, ExtJS, legacy component libraries
JSF/server-generated IDsj_idt45:username, ctl00_MainContent_txtNameJSF, ASP.NET WebForms
React useId output:r1:, :R2ab6:, «r3»React 18+ useId()
CSS ModulesButton_primary__3xYzQCSS Modules / Next.js
CSS-in-JScss-1x2y3z, sc-bdVaJa, jss123Emotion, styled-components, JSS
Angular view encapsulation_ngcontent-c12, _nghost-ng-c4012345Angular emulated encapsulation
Angular debug attributesng-reflect-model="..."Angular dev mode only, absent in production builds
Tailwind utility soupflex items-center px-4 py-2Stable per build, but describes looks, not meaning
UUIDsa3f9c2e1-...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:

  1. A dedicated test attribute: data-testid, data-test, data-qa, data-cy.
  2. Semantic and accessibility attributes: name, type, aria-label, role, for/id pairs on labels, href for links.
  3. Stable, human-assigned IDs: id="checkout-button" written by a person, not a framework.
  4. Visible text, for buttons and links whose label is part of the spec (and not translated in your test environment).
  5. A stable ancestor plus a short relative path: anchor on the nearest stable container, then descend.
  6. Partial matching on a dynamic attribute, as a last resort.
Same element, increasingly fragile locators
Selenium 4 Stable
// Best: a test hook the team maintains
driver.findElement(By.cssSelector("[data-testid='save-invoice']"));
// Good: accessible name and role
driver.findElement(By.cssSelector("button[aria-label='Save invoice']"));
// Acceptable: text that is part of the spec
driver.findElement(By.xpath("//button[normalize-space()='Save invoice']"));
// Fragile: generated class from CSS Modules
driver.findElement(By.cssSelector(".InvoiceForm_save__2kd9X"));
// Broken tomorrow: React useId output
driver.findElement(By.id(":r7:"));
# Best: a test hook the team maintains
driver.find_element(By.CSS_SELECTOR, "[data-testid='save-invoice']")
# Good: accessible name and role
driver.find_element(By.CSS_SELECTOR, "button[aria-label='Save invoice']")
# Acceptable: text that is part of the spec
driver.find_element(By.XPATH, "//button[normalize-space()='Save invoice']")
# Fragile: generated class from CSS Modules
driver.find_element(By.CSS_SELECTOR, ".InvoiceForm_save__2kd9X")
# Broken tomorrow: React useId output
driver.find_element(By.ID, ":r7:")
// Best: a test hook the team maintains
await driver.findElement(By.css("[data-testid='save-invoice']"));
// Good: accessible name and role
await driver.findElement(By.css("button[aria-label='Save invoice']"));
// Acceptable: text that is part of the spec
await driver.findElement(By.xpath("//button[normalize-space()='Save invoice']"));
// Fragile: generated class from CSS Modules
await driver.findElement(By.css('.InvoiceForm_save__2kd9X'));
// Broken tomorrow: React useId output
await driver.findElement(By.id(':r7:'));
// Best: a test hook the team maintains
driver.FindElement(By.CssSelector("[data-testid='save-invoice']"));
// Good: accessible name and role
driver.FindElement(By.CssSelector("button[aria-label='Save invoice']"));
// Acceptable: text that is part of the spec
driver.FindElement(By.XPath("//button[normalize-space()='Save invoice']"));
// Fragile: generated class from CSS Modules
driver.FindElement(By.CssSelector(".InvoiceForm_save__2kd9X"));
// Broken tomorrow: React useId output
driver.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-testid is 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", not data-testid="right-column-span-3".
  • Keys on repeated items: data-testid="order-row" plus data-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 Button component forwards a testId prop to data-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-testid from 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.

GoalCSSXPath
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')]
Partial matching on generated attributes
Selenium 4 Medium
// JSF: "j_idt45:email" -> the part after the colon is stable
driver.findElement(By.cssSelector("input[id$=':email']"));
// CSS Modules: "Button_primary__3xYzQ" -> the readable prefix is stable per component
driver.findElement(By.cssSelector("button[class*='Button_primary__']"));
// Prefix-based ID with a generated suffix
driver.findElement(By.cssSelector("[id^='order-row-']"));
# JSF: "j_idt45:email" -> the part after the colon is stable
driver.find_element(By.CSS_SELECTOR, "input[id$=':email']")
# CSS Modules: "Button_primary__3xYzQ" -> the readable prefix is stable per component
driver.find_element(By.CSS_SELECTOR, "button[class*='Button_primary__']")
# Prefix-based ID with a generated suffix
driver.find_element(By.CSS_SELECTOR, "[id^='order-row-']")
// JSF: "j_idt45:email" -> the part after the colon is stable
await driver.findElement(By.css("input[id$=':email']"));
// CSS Modules: "Button_primary__3xYzQ" -> the readable prefix is stable per component
await driver.findElement(By.css("button[class*='Button_primary__']"));
// Prefix-based ID with a generated suffix
await driver.findElement(By.css("[id^='order-row-']"));
// JSF: "j_idt45:email" -> the part after the colon is stable
driver.FindElement(By.CssSelector("input[id$=':email']"));
// CSS Modules: "Button_primary__3xYzQ" -> the readable prefix is stable per component
driver.FindElement(By.CssSelector("button[class*='Button_primary__']"));
// Prefix-based ID with a generated suffix
driver.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

Find a stable container, then search inside it
Selenium 4 Stable
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.

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']//input

The 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:

Resolve a generated ID through its label
Selenium 4 Stable
WebElement label = driver.findElement(By.xpath("//label[normalize-space()='Email address']"));
String inputId = label.getDomAttribute("for"); // e.g. ":r3:" this session
WebElement email = driver.findElement(By.id(inputId)); // By.id is safe with odd characters
label = 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

  • useId values (:r1: and variants) differ between renders and between server and client in some setups. Never hard-code them.
  • key props are not rendered to the DOM. If you need row keys, ask for a data-* 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-7ba5bd90 style attributes; the hash changes when the component changes. Ignore them.
  • Vue does not add test hooks on its own, so data-testid conventions 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

AvoidWhyInstead
Absolute XPath (/html/body/div[3]/div[2]/form/input[4])Breaks on any layout changeAnchor on a stable attribute or container
Positional indexes ((//button)[7])Breaks when an element is addedText, role, or test ID
Generated IDs and hashed classesChange per build or renderTest IDs, labels, semantic attributes
ng-reflect-*, data-v-*, _ngcontent-*Dev-only or build-specificformcontrolname, test IDs
Over-broad contains()Matches unintended elementsAdd context; verify match count
Styling classes (.btn-blue, .mt-4)Change with every redesignPurpose-based attributes
Locators copied from DevTools “Copy XPath”Usually positionalWrite by hand from stable anchors
Text in a localised UIBreaks per localeTest IDs, or pin the test locale

A Practical Checklist

When you meet a dynamic element:

  1. Reload the page twice and compare attributes. Cross off everything that changes.
  2. Look for a test attribute, then semantic/ARIA attributes, then a human-written ID.
  3. If none exist on the element, find the nearest stable ancestor or label and navigate from it.
  4. Use partial matching only on a clearly stable fragment, and check the match count.
  5. Open a ticket or pull request to add a data-testid, and link it from a code comment next to the workaround.
  6. 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, useId output, 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.

Test yourself Locator Basics 10 questions · beginner

Related lessons