πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 4 of 100
Exceptions
Advanced

Handling Stale Element Reference Exception

πŸ‚Scenario Overview

Handling Stale Element Reference Exception

Key Takeaways & Cheat Sheet

  • βœ“Identify causes (page refresh, AJAX container update, DOM replacement)
  • βœ“Never store active WebElement references across page transitions
  • βœ“Implement a robust try-catch retry mechanism to re-locate the element
  • βœ“Use WebDriverWait with ExpectedConditions.refreshed() to auto-recover

Short Direct Answer

A StaleElementReferenceException is thrown when a previously located element is no longer attached to the page DOM. This happens when the page refreshes, an AJAX request replaces a container, or a framework like React tears down and recreates elements. Because the reference ID held by the driver is now invalid, you must re-query the DOM to fetch the new, valid element reference.

⚠️ Senior Warning (Red Flag)

Avoid using @CacheLookup in Selenium Page Factory for elements that refresh dynamically. Caching references causes StaleElementReferenceException the moment the element is detached and rebuilt.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Always design your Page Objects to re-fetch elements dynamically within action methods instead of storing them as class variables. This naturally prevents stale references.

SeleniumAutomation.java
Selenium 4 + Java
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

// βœ… Solution 1: Use WebDriverWait.refreshed to auto-locate on staleness
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.refreshed(
    ExpectedConditions.elementToBeClickable(By.id("save-button"))
)).click();

// βœ… Solution 2: Implement a clean retry loop for dynamic tables
public void clickDynamicElement(By locator, int maxAttempts) {
    int attempts = 0;
    while (attempts < maxAttempts) {
        try {
            driver.findElement(locator).click();
            return;
        } catch (StaleElementReferenceException e) {
            attempts++;
        }
    }
    throw new StaleElementReferenceException("Failed to click element after " + maxAttempts + " retries.");
}