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

Resolving Intermittent Stale Element References

πŸ‚Scenario Overview

Resolving Intermittent Stale Element References

Key Takeaways & Cheat Sheet

  • βœ“Identify asynchronous elements updated by setInterval or dynamic AJAX polls
  • βœ“Wrap wait statements using ExpectedConditions.refreshed()
  • βœ“Ensure WebElements are queried dynamically rather than saved inside base constructors
  • βœ“Write clean try-catch action wrappers that automatically retry on staleness

Short Direct Answer

Stale element exceptions happen when Javascript updates the DOM and replaces an active node. To resolve this, avoid saving WebElement references as class fields. Instead, wrap your explicit waits with `ExpectedConditions.refreshed()`, which instructs Selenium to automatically re-query the DOM if the element becomes stale.

⚠️ Senior Warning (Red Flag)

Do not use Page Factory caching (@CacheLookup) for elements that render dynamically. This causes immediate stale element exceptions when the container updates.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

The refreshed() utility works by catching StaleElementReferenceException behind the scenes and immediately triggering another lookup, keeping your tests highly resilient.

SeleniumAutomation.java
Selenium 4 + Java
// βœ… Strategy: Wrap wait check in 'refreshed()' to force dynamic re-locating
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

WebElement dynamicBtn = wait.until(
    ExpectedConditions.refreshed(
        ExpectedConditions.elementToBeClickable(By.id("confirm-payment-btn"))
    )
);
dynamicBtn.click();