Understanding Stale Element Reference Exception in Selenium

On This Page What is Stale Element Reference Exception?

June 29, 2026 · 10 min read · Tool Comparison

Understanding Stale Element Reference Exception in Selenium

While testing web applications with Selenium, different types of exceptions can occur. StaleElementReferenceException is one of the most common Selenium elision.

Overview

What is Stale Element Reference Exception?

The Stale Element Reference Exception occurs when a previously located element becomes no longer valid or detached from the DOM (Document Object Model).

When does Stale Element Reference Exception occur?

  • If the HTML web element is No Longer present on the webpage
  • The Permanent cut of the Referenced Element
  • Page Reload or Navigation
  • DOM Updates via JavaScript or Ajax
  • Element Re-rendering
  • Switching Between Frames or Windows

How to handle Stale Element Reference Exception in Selenium

  • Using WebDriverWait
  • Leveraging the try-catch block
  • Using te Page Object Model
  • Refreshing the web page

In this guide, learn in detail about Stale Element Reference Exception in Selenium, covering the causes and the ways to care it.

What is Stale Element Reference Exception?

Exception is the fault or gap that come during the execution of the program at runtime. While testing web application with Selenium different types of exceptions are front unremarkably. These elision should be plow carefully to sustain the normal application flow.

StaleElementReferenceExceptionis one of the most mutual Selenium exceptions which is often coat when the web element you are prove to interact with is no longer associated with an HTML element in the DOM. As Selenium tries toreference a stale element, it throws aStaleElementReferenceException.It is one of the many subclasses of theWebDriverExceptionclass in Selenium.

Read More:

The possible reasons for the web element go stale can be:

  • a page refresh,
  • DOM update, or
  • location of the web component being alter.

However, web ingredient do not get relocated automatically, the driver creates a acknowledgment ID for the element and has a particular place in DOM that it expects to chance.

If the Selenium web driver can not find the element in the current DOM, any activity performed on that web ingredient will throw aStaleElementReferenceException.

How to Identify Stale Element Reference Exception in Selenium

It is potential to identify a Stale Element Reference Exception by analyzing the followers:

  1. Exception Message: The erroneousness message will specifically have StaleElementReferenceException mentioned, indicating that the element is no longer attach to the DOM.

Example: & # 8220; stale element reference: element is not attached to the page document & # 8221;

  1. Error Stack Trace:The stack trace will point out the line of code where the element reference get invalid.
  2. Symptoms: When interacting with a previously situate element (e.g., clicking), the exam will throw this exception if the element has been detached or modified.

Example:

try {WebElement element = driver.findElement (By.id (`` elementId '')); element.click ();} catch (StaleElementReferenceException e) {System.out.println (`` The element is no longer attach to the DOM. ``);}

This way, you can blemish the exception when it occurs and handle it.

Read More:

When does Stale Element Reference Exception occur: The Causes

If you know how Selenium works you must be aware that it tries to find a web element on the web page expend of WebDriver. It stock the reference id of that element in memory after the constituent is found. So, the adjacent clip when Selenium desire to interact with the same element, it uses the reference id instead of detect the element again.

The two most usual reasons for theStaleElementReferenceExceptionto hap are that:

  • The take web element to be interacted with is no longer present on the HTML web page
  • The take web element was destroyed completely and recreated.

1. The HTML web element is No Longer present on the webpage

There can be scenarios when the web page gets refreshed or updated due to a JavaScript operation and so the cite of the elements to be interact with gets cold leading to StaleElementReferenceException.

Let us understand with a real clip representative.

Imagine you are automatise a web application which affect filling out a registration form in which click on a language dropdown listing dynamically modify the substance of the country dropdown list.

Now, lets say your Selenium script site the state dropdown element successfully and choose the country. However, just before the selection is opt, the exploiter modify the choice from the speech dropdown and therefore the country dropdown tilt gets updated dynamically.

At this moment when the Selenium script tries to interact with the state dropdown, it encounters aStaleElementReferenceExceptionbecause the previously located dropdown element is no longer present in the DOM.

2. Lasting deletion of the Referenced Element:

There can be scenarios where the referenced element might have been permanently cancel. For example, if the web page where the element resides has been refreshed before the interaction with the element really took spot.

Let us understand with a existent time example.

Imagine you are automating an e-commerce website which involves navigating to the production, adding it to the cart and later verify the availability of the ware in the cart page.

You make a Selenium book for this scenario, nevertheless, let us say that between the clip the script clicks the “Add To Cart” push and navigates to the cart page, the item gets out of stock. At this moment when the Selenium playscript endeavor to control the front of the added item on the cart page, it find a StaleElementReferenceException.

The reference to the element in the cart become stale because the item has been permanently removed from the cart due to out of stock.

3. Page Reload or Navigation

The is rebuilt entirely as the page reloads or voyage to a new URL. Then, any element previously located by Selenium becomes stale as it no longer points to the existing DOM structure.

4. DOM Updates via JavaScript or Ajax

Countless websites utilize Ajax or JavaScript to dynamically update message without hold to recharge the page. These updates can modify, supercede, or remove elements. Thus, invalidating earlier references.

5. Element Re-rendering

or Angular etc., ofttimes update the UI by re-rendering components. During this process, old elements are replaced with new ones, leave to Selenium losing valid references.

6. Switching Between Frames or Windows

When a script change from one soma or browser window to another, elements from the previous context become unobtainable. Interacting with them throws a cold element exception.

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Read More: 

How to cover Stale Element Reference Exception in Selenium

The best way to avoid a StaleElementReferenceException is to refresh the reference of a stale factor. This means you need to create the element again by applying the locater scheme.

1. Use WebDriverWait

You can use Selenium WebDriver ’ s explicit wait method to handle StaleElementReferenceException by waiting for the ingredient to bevisible, clickable, or any other certain condition.

Instead of employ implicit wait, use explicit postponement as it allows you to wait for a certain condition to occur before performing any event on the element.

Read More:

There can be following two ways to accomplish it:

Method 1: Wait until the element is present

You can use the Explicit wait method to wait for the factor to be available before perform any activity on it.

wait.until (ExpectedConditions.presenceOfElementLocated (Web constituent locator '')))

The above line tells the WebDriver to wait until a condition is met for the element such as element to be visible or interactable.

public class ExplicitWait {public static void primary (String [] args) {// Initialize WebDriver WebDriver driver = new ChromeDriver (); // Open the webpage driver.get (`` https: //google.com ''); // Create an explicit wait WebDriverWait wait = new WebDriverWait (driver, Duration.ofSeconds (10)); // Use the explicit wait to handle StaleElementException try {// Wait until the element is present on the page WebElement ele = wait .until (ExpectedConditions.presenceOfElementLocated (By.cssSelector (`` textarea [name= ' q '] ''))); // Perform the action on the element ele.sendKeys (`` Selenium ''); System.out.println (`` Search textbook entered successfully. ``);} catch (org.openqa.selenium.StaleElementReferenceException e) {// Element became stale, handle accordingly System.out.println (`` StaleElementException occurred. Refreshing the page. ``); // Refresh the page // driver.navigate () .refresh (); // Re-locate the element after page refresh WebElement refreshedEle = driver.findElement (By.cssSelector (`` textarea [name= ' q '] '')); refreshedEle.sendKeys (`` Selenium ''); System.out.println (`` Search text recruit successfully after page refresh. ``);} // Close the browser driver.quit ();}}

Method 2: Wait until the element is refreshed

You can useExpectedConditions.refreshed ()method to subdue theStaleElementReferenceExceptionas this method will make the WebDriver wait for the constituent to be refreshen and lead its reference.

WebElement ele = wait.until (ExpectedConditions.refreshed (ExpectedConditions.presenceOfElementLocated (By.cssSelector (`` textarea [name= ' q '] ''))));

2. Use the try-catch block

The former way to handle this elision is to use atry-catchblock. The element which is suspected to throw the StaleElementReferenceException should be keep under try cube and in catch cube the web page should be refreshed and the component should be quicken again.

WebElement factor = driver.findElement (By.id (`` web element locater '')); try {element.click ();} catch (StaleElementReferenceException e) {// Refresh the page driver.navigate () .refresh (); // Try to locate the factor again element = driver.findElement (By.id (`` web element locator ``)); element.click ();}

And in some instances, the ingredient is temporarily not interactable through the DOM. In such cases, you can try to access the element for a certain number of times using a loop until it becomes interactable.

WebElement ele = driver.findElement (By.cssSelector (`` textarea [name= ' q '] '')); for (int i = 0; i & lt; 3; i++) {try {ele.click (); interruption;} gimmick (StaleElementReferenceException e) {e.printStackTrace ();}}

Here, the loop is await to run 3 times. If the element is found in the first few attempts it will break the loop and come out. Otherwise, it will keep finding it till the eyelet ends.

3. Use Page Object Model

In POM, Page Factory is an inbuilt POM construct used for initialize page object. In this pattern, using@FindByannotation to locate an element. It helps to update the reference of the web element each clip before any activeness is performed on it.

Page Factory initialise the page elements idly which imply they are initialized but when they are access within page methods.

If the elements become stale, it will mechanically reinitialize it whenever it is accessed the next time.

Read More:

Below is a sample programme to realize the Page factory structure.

public class LoginPage {individual WebDriver driver; @ FindBy (id = `` username '') individual WebElement usernameInput; @ FindBy (id = `` password '') private WebElement passwordInput; @ FindBy (id = `` loginButton '') private WebElement loginButton; // Constructor to format WebDriver and element public LoginPage (WebDriver driver) {this.driver = driver; PageFactory.initElements (driver, this);} // Method to perform login action public nullity login (String username, String watchword) {usernameInput.sendKeys (username); passwordInput.sendKeys (parole); loginButton.click ();}}

4. Refresh the web page

Refreshing a web page can sometimes aid in avoid

StaleElementReferenceException, because when Selenium refresh the web page, the browser reloads the entire DOM which helps in reinitializing the elements. So, if for any reason the element gets cold, refreshing the web page can get the element accessible again.

However, it is not a reliable answer and should be apply rattling sagely. Refreshing the web page will rebuild the DOM completely which may lead to performance issues and other complexities.

Note:This should be opted as the last solution if none of the above solution act as it will solely temporarily assist you to solve the problem.

Why is Testing on Real Devices and Browsers important?

Different device and browsers render web page differently. To ensure that a given application behaves uniformly across different pools of devices and browser, it is advisable to test it in the real devices and browsers with a real environment set up.

Testing in and browsers ensures high-quality user experience, compatibility across different platforms, and validates execution and security of the application in. BrowserStack is one such program which leverages testing any mobile or web application by providing 3500+ real devices.

Talk to an Expert

Conclusion

When a previously located constituent has become invalid because of change in the DOM, a dusty element reference exception occurs in Selenium. Its causes could include page reloads, component remotion, etc. Understanding these causes can aid QA teams acquire stable, unflawed scripts by re-locating elements or using appropriate postponement scheme.

Useful Resources for Selenium

Methods, Classes, and Commands

Configuration

XPath

Locators and Selectors

Waits in Selenium

Frameworks in Selenium

Miscellaneous

Best Practices, Tips and Tricks

Design Patterns in Selenium: Page Object Model and Page Factory

Action Class

TestNG and Selenium

JUnit and Selenium

Use Cases

Types of Testing with Selenium

Tags
74,000+ Views

# Ask-and-Contributeabout this issue with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free