top of page

Error: Stale Element Reference Exception

Error: Stale Element Reference Exception

When I was doing the project, I got this error “StaleElementReferenceException: stale element reference: element is not attached to the page document”.

Why I got this error when my locator is correct?

Sometimes it happens when we run, the xpath is not identified or not found in the DOM (Document Object Model)

What is Stale Element?

Stale means old, decayed, no longer fresh. Stale Element means an old element or no longer available element.

What is the cause of this error?

The most common causes are:

The element has been deleted entirely. (most common cause)

The element is no longer attached to the DOM

How to overcome with this error?

Solution 1:

We can overcome this by refreshing the webpage

We can use the below one-line code

Eg: driver.navigate().refresh();

driver.findElement(By.xpath(" xpath ")).click();

Solution 2:

Using Try Catch Block

find the stale element exception and reidentify the same element with the same locator

and perform the same action in the catch block.



driver.findElement(By.xpath(" xpath ")).click();


Catch( StaleElementReferenceException e)


// reidentify the same element with the same locator

driver.findElement(By.xpath(" xpath ")).click();


Solution 3:

Using ExpectedConditions.refreshed.

We can use Wait() till it gets identified

wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(" xpath ")));

We can also use ExpectedConditions.refreshed to avoid StaleElementReferenceException and retrieve the element again.

wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf(" xpath ")));

Solution 4:

Using POM

In POM,we use initElements() method which loads the elements but it won’t initialize elements.

initElements() takes latest address.

It initializes during the run time when we perform any action on the element. This process known as lazy initialization.

1,325 views0 comments

Recent Posts

See All

Exception Handling in Selenium Webdriver

What is an exception? An exception is an error that occurs during the execution of a program. However, while running a program, programming languages generate an exception that must be handled to prev


Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page