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.
| 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
// Javaorg.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:...)# Pythonselenium.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 frameOlder 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
- 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.
- The page navigated or reloaded. Every element found before the navigation is stale afterwards, including after a form submit.
- You cached elements in a list and the list refreshed. Iterating over
findElementsresults while each click updates the list. - Page objects that store
WebElementfields. A field found in the constructor goes stale the first time the page changes. PageFactory with@CacheLookupdoes the same. - 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.
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.
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.
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
WebElementlonger 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/catchblocks. - Ask developers to add stable
keyprops anddata-testidhooks; 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.
Related errors
- NoSuchElementException: the re-found element is not present (yet).
- ElementClickInterceptedException: a re-render left an overlay on top of the element.
- TimeoutException: a wait that kept hitting stale references until the budget ran out.
- NoSuchFrameException: the frame containing your element was replaced.
Go deeper
- Common Errors Diagnose and fix the most common Selenium errors and exceptions.
- Custom Wait Conditions Write your own expected conditions with lambdas and classes, wait for attribute and text changes, element counts, JavaScript state, network idleness via BiDi, and compose conditions cleanly.
- Flaky Tests: Diagnosis and Cure A systematic method for finding why a test passes sometimes: classify the failure, reproduce it deliberately, fix the root cause (timing, state, order, environment, product), and quarantine without hiding.
- Page Object Model Learn the Page Object Model (POM) design pattern for writing maintainable and scalable Selenium tests.