Skip to main content
SeleniumDecoded

StaleElementReferenceException

StaleElementReferenceException: Causes and Fixes

Fix Selenium StaleElementReferenceException (StaleElementReferenceError in JS): why elements go stale after re-renders and navigation, and how to re-find them.

Very common W3C: stale element reference Verified against Selenium 4.52.0
Exception name by language
Java org.openqa.selenium.StaleElementReferenceException
Python selenium.common.exceptions.StaleElementReferenceException
JavaScript StaleElementReferenceError
C# OpenQA.Selenium.StaleElementReferenceException

What the error means

A WebElement is not the element itself. It is a handle, an opaque ID the browser gave you for one specific DOM node at the moment you found it. If that node is removed from the document, replaced by a new node, or belongs to a page you have navigated away from, the handle points at nothing. Any call on it (click, getText, isDisplayed) fails with “stale element reference”.

The new node may look identical, with the same ID, classes and text. It does not matter. It is a different node, and your old handle does not follow it.

Waiting longer does not fix a stale element. The old reference will never become valid again; you must find the element again.

What it looks like

// Java
org.openqa.selenium.StaleElementReferenceException: stale element reference: stale element not found in the current frame
(Session info: chrome=131.0.6778.86)
For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#stale-element-reference-exception
at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:...)
# Python
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: stale element not found in the current frame
(Session info: chrome=131.0.6778.86)
// JavaScript (selenium-webdriver)
StaleElementReferenceError: stale element reference: stale element not found in the current frame
(Session info: chrome=131.0.6778.86)
// C#
OpenQA.Selenium.StaleElementReferenceException : stale element reference: stale element not found in the current frame

Older ChromeDriver versions said element is not attached to the page document. Firefox says The element with the reference 3f2c... is stale; either its node document is not the active document, or it is no longer connected to the DOM.

Common causes

  1. A front-end framework re-rendered the component. React, Angular and Vue routinely replace DOM nodes when state changes: after typing into a filter, after an XHR returns, after a sort.
  2. The page navigated or reloaded. Every element found before the navigation is stale afterwards, including after a form submit.
  3. You cached elements in a list and the list refreshed. Iterating over findElements results while each click updates the list.
  4. Page objects that store WebElement fields. A field found in the constructor goes stale the first time the page changes. PageFactory with @CacheLookup does the same.
  5. You switched frames or windows. An element found in one frame is not valid while another frame is active, and becomes stale if that frame reloads.

How to fix it

A front-end framework re-rendered the component

Store locators, not elements, and find the element immediately before you use it. When an action is known to trigger a re-render, wait for the old node to go stale, then find the new one.

Wait for the old node to go stale, then re-find
Selenium 4 Stable
WebElement oldResults = driver.findElement(By.id("results"));
driver.findElement(By.id("filter")).sendKeys("shoes");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.stalenessOf(oldResults));
WebElement results = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("results")));
old_results = driver.find_element(By.ID, "results")
driver.find_element(By.ID, "filter").send_keys("shoes")
wait = WebDriverWait(driver, 10)
wait.until(EC.staleness_of(old_results))
results = wait.until(EC.visibility_of_element_located((By.ID, "results")))
const oldResults = await driver.findElement(By.id('results'));
await driver.findElement(By.id('filter')).sendKeys('shoes');
await driver.wait(until.stalenessOf(oldResults), 10000);
const results = await driver.wait(until.elementLocated(By.id('results')), 10000);
IWebElement oldResults = driver.FindElement(By.Id("results"));
driver.FindElement(By.Id("filter")).SendKeys("shoes");
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d =>
{
try { _ = oldResults.Enabled; return false; }
catch (StaleElementReferenceException) { return true; }
});
IWebElement results = wait.Until(d => d.FindElement(By.Id("results")));

When you cannot predict exactly when the re-render happens, retry the locate-and-act pair. Keep the retry small and specific to this exception, and always re-find by locator inside the loop.

Let the wait re-find and retry on stale
Selenium 4 Stable
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.ignoring(StaleElementReferenceException.class);
String total = wait.until(d -> d.findElement(By.id("cart-total")).getText());
from selenium.common.exceptions import StaleElementReferenceException
wait = WebDriverWait(driver, 10, ignored_exceptions=[StaleElementReferenceException])
total = wait.until(lambda d: d.find_element(By.ID, "cart-total").text)
const { error } = require('selenium-webdriver');
const total = await driver.wait(async () => {
try {
return await driver.findElement(By.id('cart-total')).getText();
} catch (e) {
if (e instanceof error.StaleElementReferenceError) return false;
throw e;
}
}, 10000);
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException));
string total = wait.Until(d => d.FindElement(By.Id("cart-total")).Text);

The key detail: the lambda calls findElement every time, so each retry gets a fresh handle. Ignoring stale exceptions on a wait that reuses a captured element just loops until it times out.

The page navigated or reloaded

After any action that submits a form or follows a link, treat every previously found element as dead. Wait for something on the new page (a URL change, a heading, a unique element) and find new elements from there.

You cached elements in a list and the list refreshed

Iterate by index or by a stable key and re-find each item on every pass.

Re-find list items on every iteration
Selenium 4 Stable
By rows = By.cssSelector("#orders tr.order");
int count = driver.findElements(rows).size();
for (int i = 0; i < count; i++) {
WebElement row = driver.findElements(rows).get(i);
row.findElement(By.cssSelector("button.archive")).click();
// archiving re-renders the table; next pass finds fresh rows
}
rows = (By.CSS_SELECTOR, "#orders tr.order")
count = len(driver.find_elements(*rows))
for i in range(count):
row = driver.find_elements(*rows)[i]
row.find_element(By.CSS_SELECTOR, "button.archive").click()
const rows = By.css('#orders tr.order');
const count = (await driver.findElements(rows)).length;
for (let i = 0; i < count; i++) {
const row = (await driver.findElements(rows))[i];
await (await row.findElement(By.css('button.archive'))).click();
}
By rows = By.CssSelector("#orders tr.order");
int count = driver.FindElements(rows).Count;
for (int i = 0; i < count; i++)
{
IWebElement row = driver.FindElements(rows)[i];
row.FindElement(By.CssSelector("button.archive")).Click();
}

If clicking removes the row, the count shrinks; in that case always take the first matching row instead of index i.

Page objects that store WebElement fields

Hold By locators as fields and expose methods that find on demand. If you use Java PageFactory, remove @CacheLookup from anything that can re-render. The page object lesson shows the locator-field style.

You switched frames or windows

Find elements after switching into the context where you will use them, and re-find them if you switch away and back.

How to prevent it

  • Never keep a WebElement longer than one logical step. Locators are cheap; stale handles are expensive to debug.
  • Wait for a concrete signal that a re-render finished (old node stale, spinner gone, new text present) rather than acting the moment the new node appears.
  • Put retry-on-stale logic in one helper, like the retry stale element recipe, not scattered try/catch blocks.
  • Ask developers to add stable key props and data-testid hooks; it will not stop re-renders, but it makes re-finding reliable.
  • Track stale failures separately in your flaky test reports. They are almost always a test design issue, not an application bug.

Go deeper