Webdriver: stale: either the element is no longer attached to the DOM or the page has been refreshed

Hi All,

I have a check on each web page as follows:


public static void WaitOnPageForXPathClickable(string selector) { new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable((By.XPath(selector)))); }

All I’m trying to do is to wait until a particular element on the page is clickable before actually clicking it, but the results are intermittent. Sometimes it works fine and other times I get the following message:

OpenQA.Selenium.StaleElementReferenceException : The element reference of stale: either the element is no longer attached to the DOM or the page has been refreshed

Any ideas why this would happen?



1 Like

I had that happen. I waited until a specific item I wanted in a select list was visible, then clicked it. Sometimes it was not found.

Discovered (finally) that the javascript that built the select list ran more than once (unintentionally, I think, b/c the list did not change).

It’s hard to get the devs interested in this kind of “bug,” b/c it’s not visible to the human user.

I’m not an expert with Selenium but I’m reading about it and what I read is you need to make a mechanism that checks it found the element and retry to find it. Of course it is something with limited attempts to prevent infinite loops but overall that’s it. If it is Java you have to catch StaleElementReferenceException and retry in there.

1 Like

About WebElement: A WebElement is a reference of any visible item (Button/TextField/CheckBox/Dropdown etc) in DOM (Document Object Model).

Exception of a stale element reference is thrown in one of the two cases:

  • If an element has been deleted.
  • If an element is no longer attached to the DOM.

“OpenQA.Selenium.StaleElementReferenceException” is thrown when reference of any element is first destroyed in DOM and then recreated by any Javascripts functions. This exception is commonly thrown in these scenarios. So, the reference of element becomes stale and we are no longer to use the reference to find the element in the DOM.

The first possible solution to refresh the application instance using below code in Selenium:

  • driver.navigate().refresh();

By some of the ajax async calls in application, element is destroyed in DOM and recreated. We need to use below code to wait for the element to re-appear in the DOM.

  • wait.until(ExpectedConditions.stalenessOf(webElement));

If WebDriver throws a stale element exception in this case, even though the element still exists, the reference is lost. You should discard the current reference you hold and replace it, possibly by locating the element again once it is attached to the DOM.

Hope this solution should work for you. Please try this and let me know if you need any other help from my side.