I'd the same problem when i was doing date picker, with one of the site. I'd to get all the active (or enabled) buttons from the date picker and click each of that. When I iterated the elements it was getting stale. I'd re reiterate keeping another list. This may have happened because once the List gets selenium does not refer it back. Below is the fixed code
@Test
public void datePickerTest() throws InterruptedException{
driver.get(baseURL);
// click on flights tab
genericMethod.getElement("tab-flight-tab-hp", "id").click();
// click departing date, such that the date picker is loaded in the dom
genericMethod.getElement("flight-departing-hp-flight", "id").click();
Thread.sleep(700);
// pass the collected xpath where you can find all the dates which are enabled
String xpath=".//*[@id='flight-departing-wrapper-hp-flight']/div/div/div[2]/table/tbody/tr/td/button[not(@disabled)]";
List<WebElement> activeDatesWebElement = genericMethod.getElements("xpath", xpath);
System.out.println("Number of Active Dates " + activeDatesWebElement.size());
// work around for an element when it is found stale
List<String> activeDateListAsString = new ArrayList<String>();
for(WebElement temp : activeDatesWebElement){
activeDateListAsString.add(temp.getText());
}
// iterate all element in the list received, which is kept in list
for(String temp : activeDateListAsString){
genericMethod.getElement("flight-departing-hp-flight", "id").click();
Thread.sleep(500);
String selectDateXpath=".//*[@id='flight-departing-wrapper-hp-flight']"
+ "/div/div/div[2]/table/tbody/tr/td/button[text()='"
+temp+"']";
genericMethod.getElement(selectDateXpath, "xpath").click();
Thread.sleep(500);
}
}
WaitForPageToLoad
method that gets called when a page object opens. Then you can wait for one or two things on the page that indicate that it's ready, and then you can proceed with confidence that nothing will go stale underneath you.