Why StatleElementReferenceException is thrown?
For example let we consider the following code,
List <WebElement> alllinks = driver.findElements(By.tagName("a"));
for(WebElement link : alllinks) {
link.click(); // It may cause StatleElementReferenceException
driver.navigate().back();
}
Here the reference variable 'alllinks' has the reference of all the WebElements, those has anchor(//a) tag. Coming to below, the 'for' loop clicks on the each WebElement, then navigates to its corresponding page and comes back to the original page. Due to this navigation/refresh DOM references might be changed. But the reference variable 'alllinks' holds the previous references of WebElements. Now the reference of the element becomes 'stale'. In this case the StaleElementReferenceException is thrown.
How to handle StatleElementReferenceException?
You can avoid this StatleElementReferenceException be having following style of code,
int sizeOfAllLinks = driver.findElements(By.tagName("a")).size();
for (int index=0; index<sizeOfAllLinks; i++ ) {
getElementWithIndex(By.tagName("a"), index).click();
driver.navigate().back();
}
public WebElement getElementWithIndex(By by, int index) {
return webDriver.findElements(by).get(index);
}