October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Handle Stale Element Exceptions in Selenium with Java

A stale Selenium WebElement refers to a DOM node that is gone. Learn when to re-locate, wait for staleness or redraw, and avoid unsafe retries in Java.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When Selenium throws StaleElementReferenceException, the WebElement you saved points to a DOM node that is no longer attached to the page. Wait for the page’s expected change, then find the element again using its By locator. Avoid blindly retrying a click or other action that may already have succeeded.

What a stale element exception means

Selenium’s StaleElementReferenceException Java API documentation defines the exception as indicating that an element reference is stale because the element no longer appears in the page DOM. Selenium checks an element’s freshness when you call a WebElement method. If the check fails, that reference—and later calls through it—cannot be used. A replacement node that matches the same selector is a different DOM object.

This is a reference-lifetime problem, not necessarily a locator problem: the locator may still identify the intended element after the page changes, even though the element object you previously found is invalid.

Why Selenium elements become stale

  • Navigation or refresh: the page document changes, invalidating references to its former elements.
  • DOM updates or redraws: a client-side application may remove a node and create a replacement while updating a component.
  • Window or frame changes: Selenium may be operating in a different browsing context from the one where the element was found.
  • Timing races: the page changes between finding an element and using it.

Selenium’s troubleshooting guide recommends checking the page state, locator, DOM updates, and wait strategy. First confirm the active page, window, and frame, and whether the navigation or interaction that should precede the lookup has completed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Preferred fix: locate the current element when you need it

For a dynamic page, keep the locator rather than a long-lived WebElement. An explicit wait can locate the current matching element and check it is visible and enabled before returning it:

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

By saveButton = By.cssSelector("button.save");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

wait.until(ExpectedConditions.elementToBeClickable(saveButton)).click();

The locator-based elementToBeClickable condition returns the located element after checking its visible and enabled state. That check is not a guarantee against a redraw occurring immediately afterward; if the DOM changes between the wait and the click, handle the transition rather than assuming the click must succeed.

Wait for the old element to detach, then find its replacement

Use stalenessOf when detachment of a known element is the expected transition—for example, a results panel is replaced after refreshing results:

By resultsLocator = By.id("results");
WebElement oldPanel = driver.findElement(resultsLocator);

driver.findElement(By.id("refresh-results")).click();

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.stalenessOf(oldPanel));
WebElement newPanel = wait.until(
    ExpectedConditions.visibilityOfElementLocated(resultsLocator));

stalenessOf waits until the old reference is no longer attached to the DOM. The subsequent locator-based wait obtains the replacement. If the old panel does not detach because the application updates it in place, waiting for staleness may not express the right condition; wait for the actual content or state your test expects instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Retry a condition that can race with a redraw

If an element can be redrawn between a condition’s lookup and its check, wrap the condition in refreshed:

WebElement result = new WebDriverWait(driver, Duration.ofSeconds(10))
    .until(ExpectedConditions.refreshed(
        ExpectedConditions.visibilityOfElementLocated(
            By.cssSelector(".result"))));

Selenium’s ExpectedConditions Java API describes refreshed as allowing a condition to be retried when an element is updated or redrawn between locating it and checking it. Prefer this kind of state-focused wait to an unbounded catch-and-retry loop.

Choosing the right recovery

Situation Use Important limit
You need to interact with a dynamic element Keep a By locator and use a locator-based explicit wait at the point of use. The DOM can still change after the condition succeeds.
An action should remove a particular old element Wait for stalenessOf(oldElement), then locate the replacement. Only appropriate if detachment is actually expected.
Redraw can occur during a condition Wrap the condition with refreshed. Choose a condition that represents the desired page state.
A known transient race affects a safe operation Use a small, bounded retry: catch only StaleElementReferenceException, re-locate from the saved locator, and retry. Do not retry an action that may already have produced a side effect.

For ordinary interactions, a locator-based wait followed by a fresh lookup is usually the clearest approach. Repeated remote lookups can add latency, particularly with a remote WebDriver grid, so target the lookup and wait to the element and state you need rather than repeatedly searching without a condition. Selenium documents By locators in its Java API package reference.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common mistakes and fixes

  • Reusing a saved element after a redraw, refresh, or navigation: find it again from its locator after the change.
  • Adding a fixed Thread.sleep and assuming the page is ready: a delay does not prove the relevant state occurred. Wait for the expected element, detachment, or other meaningful condition.
  • Catching every WebDriverException: this can conceal unrelated failures. Catch the stale exception narrowly only when a retry is justified.
  • Retrying a state-changing click automatically: the first click may have succeeded before a later read went stale. Verify the resulting state before deciding whether to act again.
  • Assuming clickability prevents staleness: visibility and enabled state are checked at evaluation time; a redraw may happen before the next command.
  • Changing a valid selector unnecessarily: test whether the same locator finds the intended replacement after the update before treating the selector as wrong.

A fixed sleep can also make tests slower on fast runs while remaining too short on slow ones. Use an explicit condition for the state the test depends on.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

If your task is to capture a page rather than exercise it through Selenium, ScreenshotNeo provides a screenshot API and MCP server. A single GET request can return a PNG, JPEG, WebP, or PDF; the API handles capture rather than Selenium element interaction.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. Cookie banners, newsletter popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for free.

Frequently Asked Questions

Does a stale element exception mean my locator is incorrect?

No. The locator can still match the intended element after a redraw; the stored WebElement refers to the old DOM node.

Should I retry every action that throws a stale element exception?

No. Retry only when the operation is safe to repeat and the retry is bounded. A click may already have changed the page before a later command encountered the stale reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can elementToBeClickable prevent a stale element exception?

No. It checks visibility and enabled state when evaluated, but the DOM may change before the next WebDriver command.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.