Solution 1:
You could refresh the page and check out once more for the same element.
Assume you're attempting to click on a link and obtaining the stale element exception.
Sample code to overcome the issue
driver.navigate().refersh();
driver.findElement(By.xpath("xpath here")).click();
Solution 2:
If an element is not attached to DOM then you could try using ‘try-catch block’ within ‘for loop’
// using for loop, it tries for three times.
// If the element is found for the first time then it breaks from the for loop and comes out of the loop
for(int i=0; i<=2;i++){
try{
driver.findElement(By.xpath("xpath here")).click();
break;
}
catch(Exception e){
System.out(e.getMessage());
}
}
Solution 3:
Wait for the element till it gets available
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("table")));
Use ExpectedConditions.refreshed to avoid StaleElementReferenceException and retrieve the element again. This method updates the element by redrawing it and we can access the referenced element.
.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf("table")));
I hope this helps!
If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, enroll in industry based Selenium online courses.