StaleElementReference Exception in Selenium

StaleElementReference Exception occurs when driver is trying to perform action on the element which is no longer exists or not valid.

What causes them?

In short, a StaleElementException is calling a reference on an element that has been torn down.  There are many causes for them, here are some of the common ones I’ve seen.

  • Page Refresh – I’ve seen this commonly working with tabbed pages.  Sometimes a page will look like 1 page with multiple tabs, but really are completely separate pages.  It might look like the same tab bar, but in reality you’ll have to re-find the element in order to work with it.
  • JavaScript MVC frameworks – Many JavaScript MVC frameworks can update contents of a list or a control by rapidly tearing down and recreating the same element.  There are times an element looks like only the text is updating, but in reality the entire element is torn down and rebuilt.
  • Elements in transition – An interesting trick web developers use to create interesting transitions is to clone an section or div (and everything inside), then manipulate the clone that’s overlaid on top the actual elements.
    •  For example, to make a simple slide in transition to appear as if the old contents were sliding out and the new contents are sliding in, you could create a clone or the contents, then animate that clone to slide out while the new contents are in an identical div that’s sliding in.
  • Elements being moved or reordered – If an element disappears off the screen to be relocated, it’ll cause the original reference to go stale.
  • Elements being re-rendered – A good example is an ajax request that dumps it’s return into the page.

How to solve stale element reference exception in selenium

Solution 1

You can refresh the page and again try for the same element.

Example- If you are trying to click on an element and getting the exception then try in below format

driver.findElement(“element id”)).click();

Solution 2-

Sometimes it takes the time to attach element on Dom so you can retry using for loop and try catch..

for (int i = 0i <= 2; i++)
	try {
	catch(Exception e) {

In the above program, we will try for specific element max 3 times and if the element is located in the first shot itself then it will break from for loop and come out of the loop.

Leave a Reply

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