πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
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();