Selenium error StaleElementReferenceException: stale element reference: element is not attached to the page document
The element you found earlier no longer exists in the current DOM, because the page re-rendered after you located it and before you acted on it.
Why this happens
- The page reloaded or a JS framework re-rendered the element between the find and the interaction
- The element was inside a part of the DOM that got removed and recreated (e.g. after an AJAX update)
- You switched frames or windows and are still holding a reference from the old context
How to fix it
- Re-locate the element right before interacting with it instead of holding a reference across steps
- Wrap the interaction in an explicit `WebDriverWait` with `ExpectedConditions.refreshed(...)` to re-fetch on staleness
- Use the Page Object pattern with lazy `@FindBy` lookups instead of caching `WebElement` references
Example
// Bad: element found once, reused after the DOM changed
WebElement button = driver.findElement(By.id("submit"));
triggerRerender();
button.click(); // StaleElementReferenceException
// Good: re-locate right before acting
triggerRerender();
driver.findElement(By.id("submit")).click();