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

Handling Stale Element Reference in a Dynamic List

πŸ“‹Scenario Overview

Handling Stale Element Reference in a Dynamic List

Key Takeaways & Cheat Sheet

  • βœ“Acknowledge list items shift or refresh dynamically during iteration
  • βœ“Retrieve the size of the list or the latest dynamic index on each iteration
  • βœ“Re-query the list of WebElements inside the loop to fetch fresh references
  • βœ“Use text-based relative XPaths to select specific list elements directly

Short Direct Answer

When iterating over lists (like dynamic grids or catalog products) where clicking or hovering an item triggers an AJAX refresh, the list nodes become stale. To resolve this, instead of looping over a pre-fetched `List<WebElement>`, loop by index, re-querying the list at the beginning of each iteration to secure a fresh, active reference.

⚠️ Senior Warning (Red Flag)

Never loop over a pre-fetched List<WebElement> if clicking items triggers a list reload. The second item in your pre-fetched list will throw a StaleElementReferenceException instantly.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

By re-querying the elements inside the loop body, you guarantee the element reference matches the current state of the DOM.

SeleniumAutomation.java
Selenium 4 + Java
// βœ… Correct iteration strategy for dynamic lists
int listSize = driver.findElements(By.className("product-item")).size();

for (int i = 0; i < listSize; i++) {
    // Re-query the dynamic list at the start of every loop iteration
    List<WebElement> freshItems = driver.findElements(By.className("product-item"));
    WebElement targetItem = freshItems.get(i);
    
    // Perform action
    targetItem.click();
    
    // Navigate back if necessary or wait for reload
    driver.navigate().back();
}