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 + Javaimport 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.");
}