Selenium Dynamic Elements

Dynamic elements change their attributes, position, or existence while a page runs. Imagine a train station board. The platform number, time, and status update every minute, yet the board itself stays in place. Web pages behave the same way. An id such as btn_48213 may become btn_90771 after a refresh, and a test that trusts the old id fails.

Types of Dynamic Behavior

TypeWhat ChangesSample
Dynamic idNumbers in the id change each loadid="submit_7391"
Dynamic classFramework adds random textclass="btn css-1x9ab"
Delayed elementAppears after a server callSearch suggestions
Changing positionOrder of rows shiftsLive score list

Diagram of the Problem

Load 1:  <button id="save_101">Save</button>
Load 2:  <button id="save_582">Save</button>
Load 3:  <button id="save_947">Save</button>

Fixed part  : "save_"      -> stable
Changing part: 101 / 582 / 947 -> unstable

The solution keeps the stable part and ignores the unstable part.

Partial Match with XPath

XPath offers starts-with(), contains(), and ends-with() style checks on attributes.

driver.findElement(By.xpath("//button[starts-with(@id,'save_')]"));
driver.findElement(By.xpath("//button[contains(@class,'btn')]"));

Partial Match with CSS

CSS selectors use three symbols for partial text: caret for the start, dollar for the end, and star for any position.

driver.findElement(By.cssSelector("button[id^='save_']"));
driver.findElement(By.cssSelector("button[id$='_ok']"));
driver.findElement(By.cssSelector("button[id*='ave']"));

Anchor on Visible Text

Users read words, not ids. Visible text changes less often than generated attributes. An XPath text match mirrors the user's view.

driver.findElement(By.xpath("//button[normalize-space()='Save']"));

The normalize-space() function trims extra spaces, which protects the locator from small formatting edits.

Find Through a Stable Parent

A parent container often carries a fixed id while its children change. Start at the parent and walk down.

 div#checkoutForm  (stable)
     |
     +-- button (id changes)   -> locate with  #checkoutForm button
driver.findElement(By.cssSelector("#checkoutForm button.primary"));

Elements That Appear Late

Some elements load after a network call. A locator may be perfect, yet the element does not exist at the instant of the search. Pair the locator with an explicit wait.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement item = wait.until(ExpectedConditions
        .visibilityOfElementLocated(By.xpath("//li[contains(text(),'Laptop')]")));

Stale Element Reference

A stale element error appears when the page rebuilds an element you stored earlier. The old reference points to something that no longer exists. Fix the error by locating the element again right before each use.

Store element -> Page refreshes part of the screen -> Old reference dead
                                                      |
                                       Find again -> Fresh reference works

Choosing a Strategy

  • Ask developers for stable test attributes such as data-testid.
  • Prefer short selectors that name one stable feature.
  • Avoid absolute XPath that counts every step from the page top.
  • Avoid indexes like div[3] when the list order can change.
  • Combine a partial match with a wait for delayed content.

Key Points

  • Keep the stable fragment and drop the changing fragment.
  • Match on visible text when attributes look random.
  • Combine locators with explicit waits for late elements.
  • Re-find elements after the page refreshes.

Practice Scenario: Live Search Box

A shopping site shows suggestions while you type. The list appears after a short server call, and each suggestion carries a random id. A reliable test types the word, waits for the list container, and clicks the suggestion whose visible text matches. The container id stays fixed, the text stays readable, and the wait absorbs the network delay. This three-part recipe works on almost every dynamic page: a stable anchor, a readable match, and a patient wait.

Questions to Ask Before Writing a Locator

  • Which part of this element never changes?
  • Does a parent container hold a stable id or class?
  • Does the user see words that identify the element?
  • Does the element exist at the moment of the search?