Run End-to-End Tests from Your Terminal with Kane CLI
Author and Run Tests Right from the Terminal in Natural Language, with an Evidence-Backed Pass or Fail from a Real Browser.
npm install -g @testmuai/kane-cli
How to Handle StaleElementReferenceException in Selenium
StaleElementReferenceException means your WebElement points to a node that left the DOM. Read what each Chrome error message means and fix it in Selenium Java.
Last Updated on:
A StaleElementReferenceException in Selenium is thrown when your script acts on a WebElement that is no longer attached to the page's DOM, and you handle it by locating the element again. Selenium Java raises it as org.openqa.selenium.StaleElementReferenceException after a page reload, a browser back navigation, or a JavaScript update that replaces the node the reference pointed to.
On current Chrome versions, the error text also tells you which change caused it: stale element not found in the current frame means the page re-rendered the element in place, while stale element not found means the page reloaded or navigated. The Java examples below run against the TestMu AI Selenium Playground.
TL;DR
To handle a StaleElementReferenceException in Selenium, locate the element again with findElement() right before the action that failed. The exception means the WebElement your script holds points to a node that was removed, or to a page the browser has left, so retrying with that same reference fails again.
What Does Each Error Message Mean?
- stale element not found in the current frame: Page reloaded: no. Chrome 125 to 156 return this message when the node was removed or replaced while the page stayed loaded, such as a JavaScript re-render of a form field.
- stale element not found: On Chrome 125 to 156, this message means the page reloaded or navigated, so the reference belongs to a document the browser replaced. Chrome 120 used the same text for in-place re-renders too.
- element is not attached to the page document: Chrome 110 to 112 use this older wording for every stale reference, whether the page reloaded or the DOM re-rendered.
Which Fix Should You Use?
- Re-locate the element: Call findElement() again after any navigation, refresh, or re-render, which is the fix the Selenium documentation gives for a changed DOM.
- Retry loop: Wrap findElement() and the action in a try-catch block inside a loop capped at three attempts, for fields that a framework replaces between the lookup and the action.
- ExpectedConditions.refreshed(): Wrap a condition such as elementToBeClickable() so WebDriverWait keeps polling when the check throws StaleElementReferenceException, then act on the element the wait returns.
- By locators instead of WebElement fields: Store a By locator and find the element at the moment of each action, so no reference outlives the page it came from.
How Do You Debug a Stale Element Failure in CI?
Read the exception message first, then find the command just before it that navigated, refreshed, or changed the DOM. TestMu AI's Automation Cloud records command logs, console logs, and video for every Selenium session, so the failing command and the page state at that moment are both visible after the run.
What Is a StaleElementReferenceException?
A StaleElementReferenceException is the error Selenium WebDriver raises when a command uses an element reference that no longer points to a live element on the page.
The W3C WebDriver specification treats an element as stale when its node document is not the active document or when the node is no longer connected, and the driver answers with the error code stale element reference and HTTP status 404.
Each Selenium language binding throws it under its own name:
- Java - org.openqa.selenium.StaleElementReferenceException
- Python - selenium.common.exceptions.StaleElementReferenceException
- JavaScript - StaleElementReferenceError in the selenium-webdriver package
- C# - OpenQA.Selenium.StaleElementReferenceException
A stale reference does not switch over to a new element, even one with the same ID, text, and position on screen. WebDriver ties each reference to one node, so the fix is to find the element again.
When Does StaleElementReferenceException Occur?
The Selenium troubleshooting guide says an element goes stale when it was located earlier but can no longer be accessed, and it names the situations that cause it:
- Page refresh or DOM change - The page reloaded, or a script removed or replaced the node. Single-page apps built with React, Angular, or Vue replace nodes without any page load, so table rows, list items, and form fields that update in place go stale too.
- Navigation - The script moved to another page, so references from the previous page belong to a document that is no longer active. Coming back with navigate().back() does not reliably revive them: in 6 runs on Chrome 156, Chrome restored the home page from its back/forward cache in 2, and a link reference found before leaving worked only in those 2.
- Window or frame switch - The element belongs to a different window, frame, or iframe than the current context. On Chrome 156, using an element from an iframe after switching back to the top-level page threw NoSuchElementException with the message no such element: element not found, so check for both exceptions after a context switch.
What Does the StaleElementReferenceException Message Mean?
The text after stale element reference: comes from ChromeDriver, and its wording has changed across Chrome releases. Running the same two failures, a navigation and an in-place re-render, on Chrome 110 to 156 on the TestMu AI cloud grid returns these messages:
| Chrome versions tested | After a reload or navigation | After the node is replaced on the same page |
|---|---|---|
| 110 to 112 | element is not attached to the page document | element is not attached to the page document |
| 113 to 122 | stale element not found | stale element not found (checked on 120) |
| 125 to 156 | stale element not found | stale element not found in the current frame |
ChromeDriver's call_function.js throws stale element not found in the current frame when a node it has already referenced is no longer reachable in the current page.
A re-render leaves the old node in exactly that state, so on Chrome 125 and later the wording points to the cause.
Use the message to decide where to look:
- stale element not found in the current frame - The page did not reload. Look for a framework re-render, an AJAX refresh, or a script that rebuilt the element after your findElement() call, then locate the element again after that update or wrap the lookup in ExpectedConditions.refreshed().
- stale element not found - On Chrome 125 and later, the document changed. Find the step that navigated, refreshed, or submitted a form, and locate every element you need again after it.
- element is not attached to the page document - The browser is an older Chrome release, and this message does not separate the two causes, so check for both.
A Java test reproduces the in-place case by replacing the filter field on the Table Data Search page with a copy of itself, which is what a framework re-render does, and then typing into the old reference. It uses the BaseTest class from the next section:
@Test
public void staleAfterInPlaceReRender() {
driver.findElement(By.linkText("Table Data Search")).click();
WebElement filterByField = driver.findElement(By.id("task-table-filter"));
((JavascriptExecutor) driver).executeScript(
"const field = document.getElementById('task-table-filter');"
+ "field.replaceWith(field.cloneNode(true));");
filterByField.sendKeys("completed");
}On Chrome 156, the last line fails with this output:
org.openqa.selenium.StaleElementReferenceException:
stale element reference: stale element not found in the current frame
(Session info: chrome=156.0.8078.80)
For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#staleelementreferenceexceptionExample of StaleElementReferenceException in Selenium
The Table Data Search demo on the Selenium Playground reproduces the navigation case.
Test Scenario:
- Open the TestMu AI Selenium Playground home page.
- Click the Table Data Search link.
- Type "in progress" in the Filter by Task / Assignee / Status field.
- Go back to the home page and click the Table Data Search link again.
- Type "completed" in the same field, using the WebElement found in step 3.
Step 5 fails. The WebElement from step 3 belongs to the first copy of the Table Data Search page. Going back and clicking the link again loads a new copy of the page with a new filter field, so the old reference points to a node that no longer exists, even though an identical field is on screen.
Test Implementation:
The tests use TestMu AI's Automation Cloud, a cloud Selenium grid with 3,000+ real browser and OS combinations that records network logs, console logs, video, screenshots, and command logs for every session. The command log shows which command threw the exception, and the video shows what the page looked like when it did.
Code Walkthrough:
The BaseTest class reads the LT_USERNAME and LT_ACCESS_KEY environment variables, starts a RemoteWebDriver session on the latest Chrome on Windows 11, and opens the Selenium Playground before each test. The @BeforeMethod and @AfterMethod annotations give every test its own session, so one test's navigation never carries into the next.
For how the remote session works, see Selenium RemoteWebDriver. To target another browser or OS, generate the LT:Options values with the Capabilities Generator.
public class BaseTest {
protected RemoteWebDriver driver;
@BeforeMethod
public void setup() throws MalformedURLException {
String username = System.getenv("LT_USERNAME");
String accessKey = System.getenv("LT_ACCESS_KEY");
String gridUrl = "https://" + username + ":" + accessKey + "@hub.lambdatest.com/wd/hub";
driver = new RemoteWebDriver(URI.create(gridUrl).toURL(), getChromeOptions());
driver.get("https://www.testmuai.com/selenium-playground/");
}
public ChromeOptions getChromeOptions() {
ChromeOptions browserOptions = new ChromeOptions();
browserOptions.setPlatformName("Windows 11");
browserOptions.setBrowserVersion("latest");
HashMap<String, Object> ltOptions = new HashMap<>();
ltOptions.put("project", "Stale Element Reference Exception Blog");
ltOptions.put("build", "Selenium Playground - Table Data Search");
ltOptions.put("name", "Demo Stale Element Reference Exception");
ltOptions.put("w3c", true);
ltOptions.put("plugin", "java-testNG");
browserOptions.setCapability("LT:Options", ltOptions);
return browserOptions;
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}The test class extends BaseTest, and its first test reproduces the failure:
public class TestExampleStaleElementReferenceException extends BaseTest {
@Test
public void createStaleElementReferenceException() {
driver.findElement(By.linkText("Table Data Search")).click();
WebElement filterByField = driver.findElement(By.id("task-table-filter"));
filterByField.sendKeys("in progress");
driver.navigate().back();
driver.findElement(By.linkText("Table Data Search")).click();
filterByField.sendKeys("completed");
}
}The test types in progress, which filters the table to one task. After the back navigation, it opens the page again and types completed into the field it found earlier, and that last sendKeys() call throws:
org.openqa.selenium.StaleElementReferenceException:
stale element reference: stale element not found
(Session info: chrome=156.0.8078.80)
For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#staleelementreferenceexception
Build info: version: '4.52.0', revision: '5b37fd4 5b37fd4d98c08d6a43a0790417f91b8f6f32fb5c'
System info: os.name: 'Windows 11', os.arch: 'amd64', os.version: '10.0', java.version: '21.0.13'
Driver info: org.openqa.selenium.remote.RemoteWebDriverThe test finds the Table Data Search link again after navigate().back() instead of reusing the first reference. Chrome rebuilds the home page on some back navigations instead of restoring it from its back/forward cache, and a reused link reference then throws the same exception one step earlier.
How to Handle StaleElementReferenceException?
Every fix gives the action a reference from the current DOM. Pick one by how the element went stale:
- Re-initializing the WebElement - for a page that reloaded or navigated, when you know the exact step that replaced the document.
- Loops and try-catch blocks - for an element that a script replaces at unpredictable moments, between the lookup and the action.
- ExpectedConditions - for an element that redraws while a wait is checking it, in tests that already use explicit waits.
Re-initializing the WebElement
Find the filter field again after the second click on Table Data Search, and the test passes. The link itself is found again after navigate().back() for the same reason:
private long visibleRows() {
return driver.findElements(By.cssSelector("#task-table tbody tr"))
.stream().filter(WebElement::isDisplayed).count();
}
@Test
public void reInitializeWebElement() {
WebElement pageLink = driver.findElement(By.linkText("Table Data Search"));
pageLink.click();
WebElement filterByField = driver.findElement(By.id("task-table-filter"));
filterByField.sendKeys("in progress");
assertEquals(visibleRows(), 1);
driver.navigate().back();
pageLink = driver.findElement(By.linkText("Table Data Search"));
pageLink.click();
filterByField = driver.findElement(By.id("task-table-filter"));
filterByField.sendKeys("completed");
assertEquals(visibleRows(), 3);
}The visibleRows() helper counts the table rows the filter leaves visible. The test passes on Chrome 156: in progress leaves one task, and completed leaves three.

Using Loops and Try-Catch Block
A retry loop helps when a script can replace the element after findElement() returns but before the action runs, as a framework re-render does. Each pass calls findElement() again inside a try-catch block, so a retry always works with a fresh reference, and a cap on attempts stops a real failure from looping forever.
While Loop and Try-Catch Block
The retryUsingWhileLoop() helper takes the driver, a By locator, and the text to type. It returns true as soon as sendKeys() succeeds, and false after three stale attempts:
public static boolean retryUsingWhileLoop(WebDriver driver, By locator, String value) {
int attempts = 0;
while (attempts < 3) {
try {
driver.findElement(locator).sendKeys(value);
return true;
} catch (StaleElementReferenceException e) {
attempts++;
}
}
return false;
}The test passes the same By locator before and after the navigation, so no WebElement reference survives the page change:
@Test
public void testRetryUsingWhileLoop() {
driver.findElement(By.linkText("Table Data Search")).click();
By filterByField = By.id("task-table-filter");
assertTrue(retryUsingWhileLoop(driver, filterByField, "in progress"));
assertEquals(visibleRows(), 1);
driver.navigate().back();
driver.findElement(By.linkText("Table Data Search")).click();
assertTrue(retryUsingWhileLoop(driver, filterByField, "completed"));
assertEquals(visibleRows(), 3);
}Both calls succeed on the first attempt, because each one finds the field on the current page. The loop retries only when the field is replaced during the call itself.
For Loop and Try-Catch Block
The for loop version keeps the attempt counter in the loop header and returns true on the first successful sendKeys():
public static boolean retryUsingForLoop(WebDriver driver, By locator, String value) {
for (int attempts = 0; attempts < 3; attempts++) {
try {
driver.findElement(locator).sendKeys(value);
return true;
} catch (StaleElementReferenceException e) {
// The DOM replaced the element after findElement(); the next pass finds it again
}
}
return false;
}The test is the same as the while loop test, with the other helper:
@Test
public void testRetryUsingForLoop() {
driver.findElement(By.linkText("Table Data Search")).click();
By filterByField = By.id("task-table-filter");
assertTrue(retryUsingForLoop(driver, filterByField, "in progress"));
assertEquals(visibleRows(), 1);
driver.navigate().back();
driver.findElement(By.linkText("Table Data Search")).click();
assertTrue(retryUsingForLoop(driver, filterByField, "completed"));
assertEquals(visibleRows(), 3);
}The two helpers behave the same way, so use the loop form your codebase already follows.
Using ExpectedConditions
A page script can redraw an element while a wait is still checking it. ExpectedConditions.refreshed() covers that case: it runs the wrapped condition inside a try-catch block and returns null when the condition throws StaleElementReferenceException or NoSuchElementException, so WebDriverWait treats the check as not yet met and polls again. More conditions are covered in ExpectedConditions in Selenium.
public static void chainMultipleExpectedConditions(WebDriver driver, By locator, String value) {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
WebElement element = wait.until(
ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(locator)));
element.sendKeys(value);
}The helper creates a WebDriverWait with a five-second timeout. elementToBeClickable() locates the field and checks that it is visible and enabled, and refreshed() turns a stale element during that check into another poll.
The wait returns the element it found, and the helper types into that element instead of calling findElement() a second time. If the field never becomes clickable within five seconds, the wait throws TimeoutException. The test calls the helper before and after the navigation:
@Test
public void testChainExpectedConditions() {
driver.findElement(By.linkText("Table Data Search")).click();
By filterByField = By.id("task-table-filter");
chainMultipleExpectedConditions(driver, filterByField, "in progress");
assertEquals(visibleRows(), 1);
driver.navigate().back();
driver.findElement(By.linkText("Table Data Search")).click();
chainMultipleExpectedConditions(driver, filterByField, "completed");
assertEquals(visibleRows(), 3);
}For an element you already hold, ExpectedConditions.stalenessOf() waits until that element is no longer attached to the DOM, which tells you an update has finished replacing it.
On Chrome 156, the four tests that apply a fix pass, and the two that demonstrate the exception fail with the messages shown earlier.
Note: To run these tests across 3,000+ browser and OS combinations, start free on TestMu AI and copy LT_USERNAME and LT_ACCESS_KEY from your dashboard credentials into environment variables.
For a full walkthrough in Java, watch this Selenium 4 tutorial on handling StaleElementReferenceException:
For the other errors WebDriver throws, see these common Selenium exceptions.
How Do You Prevent StaleElementReferenceException in Selenium?
You prevent a StaleElementReferenceException by locating each element right before you use it and by waiting for DOM updates to finish. Handling the exception recovers a failed step, while prevention stops the stale reference from being created.
The following practices keep element references current in Selenium Java tests:
- Store locators, not elements - Keep a By locator in a field and call findElement() at the moment of each action. A WebElement saved earlier can point to a node that no longer exists.
- Re-locate after navigation - Find elements again after navigate().back(), navigate().refresh(), or any click that loads a new page. Each page load builds a new document, and a back navigation brings the old one back only when the browser serves it from its back/forward cache, so treat every reference from before the navigation as stale.
- Wait for the old element to detach - Pass the old reference to ExpectedConditions.stalenessOf() after the action that triggers the update. The wait returns once the old node leaves the DOM, so the next findElement() call returns the new node.
- Retry inside the wait - Call ignoring(StaleElementReferenceException.class) on a WebDriverWait and locate the element inside the until() function. The wait then repeats the lookup until it succeeds or the timeout expires. Capybara builds that retry into its finders and matchers, as the Capybara flaky tests guide shows for Rails system tests.
- Switch back before reuse - An element found inside a frame or another window works only in that context. Switch back with switchTo() before you use it, or locate it again in the current context.
- Avoid @CacheLookup on dynamic elements - A PageFactory field with the FindBy annotation finds the element again on every call. Adding @CacheLookup keeps the first result, which goes stale when the page re-renders that element.
Stale element failures that depend on timing or on the back/forward cache come and go between runs, so they show up as flaky tests rather than steady failures. Test Insights, part of TestMu AI's test intelligence suite, detects flaky tests and clusters failures by error message, so the stale element failures in a build land in one group and show whether one test or a whole page object keeps hitting the exception.
Conclusion
Search your suite for WebElement fields and variables that are reused after a navigate() call, a refresh, or a click that loads a page, and replace them with By locators that you resolve right before each action. When a stale error still appears, read its message: in the current frame sends you to a re-render, and plain stale element not found sends you to a navigation.
To run the same tests on the cloud grid, follow the setup guide for Java with Selenium.
Testing from the terminal? Kane CLI by TestMu AI lets SDETs and developers plan, write, run and debug tests from the command line.
Author
Mohammad Faisal Khatri is a Software Testing Professional with 17+ years of experience in manual exploratory and automation testing. He currently works as a Senior Testing Specialist at Kafaat Business Solutions and has previously worked with Thoughtworks, HCL Technologies, and CrossAsyst Infotech. He is skilled in tools like Selenium WebDriver, Rest Assured, SuperTest, Playwright, WebDriverIO, Appium, Postman, Docker, Jenkins, GitHub Actions, TestNG, and MySQL. Faisal has led QA teams of 5+ members, managing delivery across onshore and offshore models. He holds a B.Com degree and is ISTQB Foundation Level certified. A passionate content creator, he has authored 100+ blogs on Medium, 40+ on TestMu AI, and built a community of 25K+ followers on LinkedIn. His GitHub repository “Awesome Learning” has earned 1K+ stars.
Reviewer
Navin Chandra is a Member of Technical Staff at TestMu AI, building the open-source automation that powers its Selenium and Appium cloud grid. A committer to both Selenium and Appium, he implemented WebDriver BiDi support in Selenium for real-time browser events and bidirectional control and is developing Apple's iOS RemoteXPC protocol in Appium to enable low-level wireless communication with iOS system services. He contributes to Selenium across multiple language bindings as a member of the Selenium GitHub organization. He has served as a Google Summer of Code mentee and mentor at openSUSE and an LFX mentee at CNCF's KubeArmor, and is a SUSE Certified Deployment Specialist. Navin holds a B.Tech in Computer Science.
Stale Element Exception in Selenium FAQs
Did you find this page helpful?
More Related Blogs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance
- Advanced access controls
- Advanced data retention rules
- Advanced Local Testing
- Premium Support options
- Early access to beta features
- Private Slack Channel
- Unlimited Manual Accessibility DevTools Tests














![Selenium With Java: A Hands-On Tutorial [2026]](https://assets.testmuai.com/resources/images/How-to-Use-Selenium-With-Java.png)




![A Complete Guide To Exception Tests In TestNG [With Examples]](https://assets.testmuai.com/resources/uploads/2023/04/unnamed2520-25202023-04-14T155310.134.png)
