Stale Element Reference Exception

Ever had your test break because of “StaleElementReferenceException”? There can be a couple of reasons this happens:

  1. The element has been deleted entirely. (For example after a page refresh)
  2. The element is no longer attached to the DOM. (For example with tabbed ui’s, certain tabs are not displayed until needed)
  3. The element changes type, but keeps the same locator semantics. (For example on focus a textfield gets set as password field by Javascript)

All good and fun, but breaking tests for whatever reason need to be avoided. By using the code snippet below in your element locating method you can gracefully handle “StaleElementReferenceException”. The logic for how you want to handle the exception should be placed in the catch.

public boolean isStale(WebElement element) 
    try {
        return false;
    } catch (StaleElementReferenceException sere) {
        return true;

Leave a Reply

Your email address will not be published. Required fields are marked *