Beyond the Basics: Handling Stale Elements in Selenium with Ease

Meris Stupar
4 min readMay 15, 2024

What is Stale Element Reference Exception?

A Stale Element Reference Exception is thrown by Selenium WebDriver when an action is attempted on a web element that is no longer attached to the DOM. This can happen for several reasons:

  • The element is no longer attached to the DOM due to a page refresh, navigation, or an asynchronous update.
  • The element has been replaced with a similar element — with the same attributes and values due to a dynamic change in the DOM.

What is DOM?

The Document Object Model (DOM) serves as a programming interface for web documents. It provides a structured representation of the page, enabling programs to modify the document’s structure, style, and content. In the DOM, the document is depicted as nodes and objects, allowing various programming languages to interact with and manipulate the webpage.

DOM — Document of Object Model

More about DOM — please go visit this link from MDN Web Docs — Introduction to the DOM.

DOM explained in 5 minutes from Bro Code:
Visit this YouTube video: The JavaScript DOM explained in 5 minutes!

Why Does It Happen?

Web applications today are often built with dynamic content that changes without a full page reload. Frameworks like Angular, React and Vue.js frequently update the DOM as a part of their functionality. When Selenium retrieves a reference to an element in the DOM and the DOM updates (removing or altering element) any subsequent calls to that element will result in a Stale Element Reference Exception.

A Stale Element Reference Exception occurs when an element that was previously accessible on a webpage becomes unreachable. This typically happens because the webpage’s Document Object Model (DOM) has changed after the element was initially identified but before it was accessed again. The web driver, which interacts with the page, tracks elements based on their locations in the DOM. When these elements move or are no longer present in the DOM, any attempt to interact with them will trigger this exception.

Selenium WebDriver Architecture:

How to Handle It?

Handling a Stale Element Reference Exception requires a strategic approach to either avoid the situation or recover gracefully:

  • Check Element Presence: Before interacting with an element, check if its present and visible. This can be done using methods like isDisplayed(), isVisible() to ensure the element is not only present but also visible to the user.
  • Wait for Elements Properly: Untilize explicit waits (WebDriverWait in combination with ExpectedConditions) to wait for certain condition to be true before interacting with elements. This can include waiting for an element to be visible, clickable, or for a DOM to be stable.
  • Retry Mechanism: Implement retry logic in your scripts. If a Stale Element Reference Exception is caught, you can retry finding the element and performing the action again and again. This is particularly useful in environments where the DOM changes frequently.
  • Understanding the Applications Behavior: Understanding how and when your application updates its DOM can help you better anticipate issues related to stale elements.

Solutions:

Simple solutions to avoid Stale Elements in Selenium. This issue may arise if a DOM operation on the page temporarily renders the element inaccessible. To handle such situations, you could attempt to access the element multiple times within a loop before definitively throwing an exception.

Try-catch block with explicit wait:

To effectively handle Stale Element Reference Exception, you can utilize the ExpectedCondtions.Refresh method. This approach ensures that the WebDriver waits for the targeted web element to be updated and stabilized before interacting with it. Here’s how you can implement the refreshed method for a web element:

public void waitStaleElement(By locator, int maxRetries, int waitTimeInSeconds) {
WebDriverWait explicitWait = new WebDriverWait(driver, Duration.ofSeconds(waitTimeInSeconds));
int attempt = 0;
while (attempt < maxRetries) {
try {
explicitWait.until(ExpectedConditions.refreshed(ExpectedConditions.presenceOfElementLocated(locator)));
// You can do some action on the element. Web element = explicitWait.until(ExpectedConditions.refreshed(ExpectedConditions.presenceOfElementLocated(locator)));
// element.click()
return;
} catch (TimeoutException | ElementNotInteractableException | StaleElementReferenceException e) {
System.out.println("Attempt " + (attempt + 1) + ": Element not ready yet, retrying...");
attempt++;
}
}

throw new RuntimeException("Element not ready after " + maxRetries + " attempts");
}

In this example, we establish a WebDriver wait for a certain number of seconds that you set dynamically seconds. This delay allows the WebDriver to pause until the specified web element becomes visible following any DOM manipulations on the page. Employing the refreshed method is particularly useful when anticipating DOM updates, as it helps ensure that the WebDriver waits sufficiently for the element to be accessible for interaction.

Refreshing the web page:

driver.navigate().refersh();
driver.findElement(By.xpath(Locator Here)).click(); // XPath Selector
driver.findElement(By.cssSelector(Locator Here)).click(); // CSS selector

In conclusion, the Stale Element Exceptions is a frequent issue encountered during Selenium testing. By now, you should have a clearer understanding of what this exception entails and how to address it effectively.

Simple Wait:

Incorporate a simple wait by using Thread.sleep to pause execution for a few seconds, or slightly longer depending on how long you anticipate your application will need to load the component. Implement this pause before you attempt to locate the element with find element.

More About Stale Element — Understanding Common Errors.

If you come across any alternative methods for resolving Stale Element Exceptions, feel free to share your insights in the comments section below.

Until Next Time: ✌️💻

--

--

Meris Stupar

Software Engineer - Automation Quality Assurance Engineer