What is StaleElementException in WebDriver?

This is was one old post that was hanging in my drafts… Never late to publish it..

Literary meaning of Stale: Old,decayed, no longer fresh… Exactly that is what referenced here.

Stale Element – An element that is found on a web page referenced as a WebElement in WebDriver then the DOM changes (probably due to JavaScript functions) that WebElement goes stale.

When you try to interact with the staled WebElement, the StaleElementException is thrown.

Another probable reason would be that the WebElement that is referenced had been deleted while DOM changes.


If Javascript updates the page between the findElement call and the click call then It will throw a StaleElementException.

This might not occur often, but when you get to know that the website that you are automating has lot of JavaScripts calls or AJAX calls then assume that this StaleElement Exception will occur sometime and its better to be cautious while scripting.

Mostly we will be working sitting inside a framework(DataDriven, Hybrid) what ever..

All the WebDrive API’s will be wrapped and we will use the framework API while scripting. Shortly a DSL While
doing so its better to wrap it as below

– Haven’t tested the code, but you could try something similar.

The above code snippet should work and prevent us from the StaleElementException.
We have used for loop here to keep on trying for at least 3 times and once it is found we break the loop and come out other wise it will try for another time until max of 3 times. While its failing to find on the first attempt due to the DOM changes it should get succeeded while trying second time.

Another suggestion would be to try the below idea of referencing the locator as a string and using it.

Rather than referencing it using the WebElement we can use it by String, because String doesn’t go stale.

3 thoughts on “What is StaleElementException in WebDriver?”

  1. Referencing the locator as a string saved my day. The only stable solution I could find without having to retry multiple times. Thanks.

  2. StaleObjectReference could be a real nightmare. I got the idea of StableWebElement – a wrapper which could detect Stale reference situation and try to find a new reference to the original element. All method for locating WebElement in my test always return StableWebElement wrapper and the problem with StaleObjectReferenceException disappeared.

    The C# implementation is available on my project’s page but I think it could be easily
    translated into java https://github.com/cezarypiatek/Tellurium/blob/master/Src/MvcPages/SeleniumUtils/StableWebElement.cs


Leave a Comment