What Is a Stale Element and How to Fix It

What is a
Stale Element
and how
to fix It

Stale Element

Avenga code experts are big fans of sharing their experience with technologies and sophisticated solutions.

If you are reading this you must have encountered Stale Element.

As you may already know a ‘Stale Element’ means == an old, outdated element…

An element can become outdated if a page is changed somewhere in between element declaration and actual use of element. (changes are usually caused by JavaScript, Ajax,JQuery etc.)

A common scenario looks like this:

Element declaration => Actions that cause changes(JS,Ajax etc.) => use of element => Stale Element exception.

The simple example is:

/*
WebElement element = driver.findElement(By.id(“search button”)); //we declare the element
element.click()              // this action triggers some updates (page/table refresh etc.)
…
element.click()                                        // this line would give stale element exception
*/

There are two possible ways to get Stale Element exception:

  • The element has been replaced entirely.

In first case: JS library or Ajax replaced an element with another one with the same ID or attributes. This element may look identical but it is different; the driver does not know if the replaced element is actually what’s expected and will give a Stale Element exception.

A common technique in a web app is to prepare DIVs for each tab, but only attach one at a time. Your code might have a reference to an element that is no longer attached to the DOM (that is, that has an ancestor which is “document.documentElement”).

How to fight and avoid stale elements

There are many ways of dealing with Stale Element Exception on the web. Here I gathered the ones that I personally find most useful.

  • A good practice is to use @FindBy annotation because of Lazy Initialization This way elements will be initialized right before actual usage.

Example: @FindBy(xpath=”someXpath”) public WebElement someElement;

  • Use wait methods for JavaScript, Ajax, Jquery etc. This will solve the “Race condition” that causes this exception to occur.

Examples

This method waits for all jQuery to finish.

public void waitForAjax() {

This method waits for page to be loaded.

public void waitForAjax() {
new WebDriverWait(driver, waitTimeout).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
JavascriptExecutor js = (JavascriptExecutor) d;
return (Boolean) js.executeScript(“return jQuery.active == 0”);
}
});
}

More common practice is to use try catch in a loop.

public void waitForPageToLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript(“return                            document.readyState”).equals(“complete”);
}
};
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}

NOTE: This approach is not very flexible and should only be used if ‘Stale Element’ cannot be prevented by other means. Also we should always put a system.out message into catch block, this will spare you few hours if you get an error anyway.

Working with lists solution

If you have a piece of code similar to this one:

List<WebElement> elements = driver.findElements(By.xPath(“someXpath”));
for(WebElement element : elements) {
// your code should be here
}

Try changing it to a format below. Doing so your element will be declared directly before actual usage.

int listSize = driver.findElements(By.xPath(“someXpath”)).size();
for(int i = 1; i <= listSize; i++) {
String locator = someXpath+’[’+i+’]’;
WebElement element = driver.findElement(By.xPath(locator));
// your code should be here
}

Hope this information was helpful. Try preventing the problem so you won’t have to fix it later!

Other articles

or

Book a meeting

Zoom 30 min

or call us+1 (800) 917-0207

Start a conversation

We’d like to hear from you. Use the contact form below and we’ll get back to you shortly.