How to handle StaleElement Reference Exception in Selenium Webdriver Example

A stale element reference exception is thrown in one of two cases, the first being more common than the second:

  • The element has been deleted entirely.
  • The element is no longer attached to the DOM.



public void getData(){
    WebElement table = findElementById("table");
    List<WebElement> allRows = table.findElements(By.tagName("tr"));
    for (WebElement row : allRows)
            List<WebElement> cells = row.findElements(By.tagName("td"));
            for (WebElement cell : cells)
                WebElement listName = cell.findElement(By.xpath
                  ("./* [text()='data_']"));
    }catch(Exception exception){
      System.out.println(“Exception:” + exception.toString());


On executing above test, stateElementReferenceExpection occurred while fetching the rows from the table


This caused due to the 2nd point mentioned above. The element is no longer attached to the DOM.


This exception is thrown when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference of the element.


Wait for the element till its gets available


  • 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.


From Around The Web

From the web