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();
}