QA Interview Hub · Knowledge base · Quizzes · Українська

Selenium + Java › Locators and waits

StaleElementReferenceException and other common interaction exceptions

StaleElementReferenceException means the DOM node a WebElement reference points to was removed or replaced, so the reference has gone stale. It is not a locator error. The By is stored rather than the WebElement, the test waits for the new page state and finds the element again before the action. A retry through FluentWait is added only for real redrawing.

Selenium · Exceptions

The element was on screen a moment ago, yet the click throws StaleElementReferenceException. Where did it go?

A test opens a table, stores a list of rows, applies a filter and tries to read the text from the stored rows. The rows on screen look the same, but Selenium throws StaleElementReferenceException. This is Selenium's best-known exception, and it is not about a wrong locator: the page simply replaced the nodes with new ones. The lesson covers what a WebElement really is, why a reference goes stale, how to treat this exception and what the other interaction exceptions mean.

How it works and why. As described in the lesson “How Selenium WebDriver works: client, protocol, driver, browser”, findElement returns not the element itself but its reference (a unique identifier of a node in the current document). All later commands (click, getText) are addressed to that reference. While the node lives in the DOM, everything works. If the app removed the node or replaced it with a new one (a list re-render, an SPA navigation, assigning innerHTML), the old reference points nowhere, and any action throws StaleElementReferenceException. From outside the element may look unchanged, since the new node is the same, but for the driver it is a different object.

The life of an element reference

1. findElement returns a referenceit points to a DOM node2. The app replaces the nodere-render, innerHTML, SPA3. An action on the old referenceStaleElementReferenceException4. Find again by Bya new reference to the new node
Figure 1. The cure is one: do not hold a reference, search by By right before the action.

Example: a stored list after a filter.

List<WebElement> rows = driver.findElements(By.cssSelector("tr.item"));
driver.findElement(By.id("filter-active")).click(); // table re-rendered
for (WebElement row : rows) {
    row.findElement(By.cssSelector(".name")).getText(); // Stale!
}

After the click on the filter the table is re-rendered, and rows holds references to the old rows. There are two wrong reactions: wrap it in try/catch with Thread.sleep and retry (this hides the cause and makes the test slow) or conclude the locator is wrong. The correct fix: wait for the new page state before reading, and find the elements again.

driver.findElement(By.id("filter-active")).click();
wait.until(ExpectedConditions.numberOfElementsToBe(
    By.cssSelector("tr.item"), 3));         // waited for the new state
List<String> names = driver
    .findElements(By.cssSelector("tr.item .name")).stream()
    .map(WebElement::getText)
    .toList();                               // found and read at once

Here the wait is not for "any row" but for a specific state: the number of rows after the filter. Then the elements are found and read in one expression, so there is almost no time between lookup and use for a re-render. The general rule: store the By (it describes how to find and never gets stale), not the WebElement. In a Page Object this is natural: the locator sits in a field and the element is found in a method.

For a node that is re-rendered during the action itself, the cure is a retry that searches anew each time. FluentWait can ignore the exception for the length of the timeout, while ExpectedConditions.refreshed(...) and stalenessOf(element) help to wait for the node to be replaced:

// retry an action on a node that is re-rendered during the click
WebElement button = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(10))
    .ignoring(StaleElementReferenceException.class)
    .until(d -> {
        WebElement b = d.findElement(By.id("pay")); // fresh every time
        b.click();
        return b;
    });

Other common interaction exceptions:

ExceptionWhat it meansWhat to do
NoSuchElementExceptionno element: not yet there, in another iframe or a wrong locatorwait for it to appear, check the context and the locator
ElementClickInterceptedExceptionanother element took the click (a spinner, a modal, a sticky header)wait for the overlay to go or scroll the element into view
ElementNotInteractableExceptionthe element is in the DOM but cannot be used: hidden or zero-sizedwait for visibility, check it is the right element
TimeoutExceptionan explicit wait did not reach its conditionread which condition was awaited rather than raising the timeout
SessionNotCreatedExceptiondriver and browser are incompatible or the browser failed to startversions, options, permissions, container memory
NoSuchSessionExceptionthe session is already closed (quit) or the browser crashedfind who closed it and whether the driver is shared between threads

Limits and alternatives. A script with executeScript("arguments[0].click()", el) bypasses click interception, but it also hides the real problem: a user could not make such a click, so the test passes and the interface bug remains. It is a last resort that needs an explanation in the code.

// a last resort: bypasses interception, but a user could not click like this
((JavascriptExecutor) driver)
    .executeScript("arguments[0].click()", element);

Automatically catching StaleElementReferenceException in every method is also a trap: it masks an unsynchronised test. First fix the waits (the lesson “Waits: implicit, explicit, fluent”), and add a retry only for a genuine re-render during the action. In Playwright a locator is a recipe for finding that runs every time, so this exception does not exist there by design.

Common mistakes.

  • Storing a WebElement in a class field or a list for the whole test: after the first page update the reference goes stale.
  • "Curing" the exception with try/catch and an arbitrary sleep: the test becomes slow and the cause stays.
  • Raising the timeout on TimeoutException without reading the condition: this only postpones the failure.
  • Catching a general Exception and carrying on: NoSuchSessionException after quit() becomes a silent error.

Check yourself

A Page Object keeps a private final WebElement submit found in the constructor. After navigation inside an SPA, submit.click() throws StaleElementReferenceException. What should change?

Answer

Store a By (private final By submit) and find the element inside the method right before the click, waiting for it to be clickable. A reference found once in the constructor goes stale as soon as the app re-renders the node.

Which exception does a click on a button give when it is in the DOM but under the dimmed backdrop of a modal, and how does it differ from ElementNotInteractableException?

Answer

ElementClickInterceptedException: the click would land on another element (the backdrop). ElementNotInteractableException means the element itself cannot be used at all (hidden, zero size). In the first case wait for the overlay to go, in the second find out why the element is not visible.

In an interview. Junior: StaleElementReferenceException means the element I hold a reference to has already been replaced in the DOM. I find it again before the action rather than keeping it long. Middle/Senior: A WebElement is a reference to a node, so I store the By, wait for the new page state and only then find the elements. I add a retry through FluentWait ignoring the exception only for a genuine re-render during the action, and I use a JavaScript click only with a written reason, since it hides interface defects.

More articles in this chapter