Skip to content
Latchkey

Selenium "StaleElementReferenceException" - Re-find Elements

You held a reference to a DOM element, then the page re-rendered (a re-fetch, a framework update, a navigation). The old reference now points at a node that no longer exists, so Selenium throws a stale-element error.

What this error means

An action on a previously-found element fails with "StaleElementReferenceException: element is not attached to the page document." It often appears after an action that updates the page between locating and using the element.

Selenium output
StaleElementReferenceException: Message: stale element reference:
element is not attached to the page document
  (Session info: chrome=123.0.0.0)

Common causes

DOM re-rendered after the element was found

A SPA re-render, an AJAX update, or a partial navigation replaces the node. The cached WebElement still references the detached old one.

Reusing an element across a state change

Finding an element, triggering an action that mutates the list/row it lives in, then reusing the original handle hits a node that has been swapped out.

How to fix it

Re-find the element after the change

Locate the element again right before interacting, and wait for the post-update DOM to settle.

Test.java
// Java example
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.id("save"))).click();
// re-locate rather than reusing a cached WebElement

Retry the interaction on staleness

  1. Wrap the find-and-act in a short retry that re-locates on StaleElementReferenceException.
  2. Prefer locating just-in-time over storing WebElements across actions.
  3. Wait on the new content (an expected condition), not a fixed sleep.

How to prevent it

  • Locate elements just before use; avoid caching handles across updates.
  • Use explicit waits on the post-update state.
  • Wrap interactions in a re-locate-on-stale helper.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →