Back to All Scenarios
Scenario 19 of 100
Exceptions
Advanced
Element Becomes Stale Just After Locating It
πScenario Overview
Element Becomes Stale Just After Locating It
Key Takeaways & Cheat Sheet
- βRecognize that React/Angular page updates detach old nodes from the active DOM
- βAvoid saving WebElement variables across complex page changes or refreshes
- βUse dynamic lambda expressions in WebDriverWait to re-query the element dynamically
- βApply a try-catch retry mechanism to re-locate the element on failure
Short Direct Answer
If an element becomes stale right after you locate it, the page's JavaScript detached it and attached a copy. To handle this, write inline query logic in your actions, use ExpectedConditions.refreshed() to wrap your wait statements, or write a clean retry wrapper that re-locates the element from scratch on staleness.
β οΈ Senior Warning (Red Flag)
Never attempt to re-use an element instance after a form submit, page refresh, or AJAX update. Re-query the DOM every single time.
π‘ STAR Deep Dive Explanation & Pro Tip
By wrapping the ExpectedCondition with refreshed(), Selenium automatically queries the DOM again for the element if a StaleElementReferenceException is encountered during verification.
SeleniumAutomation.java
Selenium 4 + Java// β
Strategy: Wrap wait condition in Refreshed to auto-retry locator
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.refreshed(
ExpectedConditions.elementToBeClickable(By.id("submit-order"))
)).click();