📣 Requestly API Client – Free Forever & Open Source. A powerful alternative to Postman. Try now ->

How to Handle Stale Element Reference Exception in Selenium

Rohit Rajpal
Learn how to handle Stale Element Reference Exceptions in Selenium with causes, techniques, and best practices for stable automation scripts.
How to Handle Stale Element Reference Exception in Selenium

In Selenium automation, a Stale Element Reference Exception occurs when a script tries to interact with an element that is no longer attached to the current DOM. This often happens on dynamic pages where elements reload, update, or get replaced. Ignoring this exception can lead to flaky tests and inconsistent results.

Handling these exceptions effectively requires a combination of strategies such as explicit waits, proper use of the Page Object Model, try-catch handling, and refreshing elements when necessary.

This article explains the common causes of a Stale Element Reference Exception in Selenium and provides detailed techniques to identify and handle it for more reliable test automation.

Understanding Stale Element Reference Exception in Selenium

A Stale Element Reference Exception occurs when Selenium tries to interact with a web element that is no longer part of the current DOM. Selenium uses WebElement objects to represent elements at a specific moment.

When the DOM changes due to page reloads, JavaScript actions, or dynamic updates, the stored WebElement becomes invalid. Any operation on it, such as click(), sendKeys(), or getText(), triggers the exception.

This exception is different from a locator error. The element may appear on the page, but its reference in Selenium is no longer valid. Testers must consider timing and dynamic behavior of the page when working with elements.

Key points to note:

  • WebElement references are temporary: They do not update automatically when the DOM changes.
  • Dynamic pages increase risk: Pages using AJAX, JavaScript, or frameworks like React often re-render elements without a full reload.
  • Interaction timing affects stability: Performing actions immediately after page updates increases the chance of stale element exceptions.

Common Causes of a Stale Element Reference Exception

Selenium throws a Stale Element Reference Exception when the element reference it holds becomes invalid due to changes in the DOM. These changes can happen in multiple ways. Understanding the specific causes helps testers write more robust scripts and reduce flaky tests.

Below are the most frequent scenarios:

1. Element Removed from the Webpage

When an element is removed from the page entirely, any existing WebElement reference becomes stale. This commonly happens when content is dynamically hidden or deleted. For example, clicking a “Delete” button on a table row removes that row from the DOM. Any subsequent operation on that row’s element triggers a stale reference exception.

2. Permanent Deletion of an Element

Similar to temporary removal, some elements are permanently deleted after a user action or server response. This occurs in forms, modals, or lists where elements are not re-rendered. Selenium cannot interact with deleted elements because their original reference no longer exists in the DOM.

3. Page Reload or Navigation

When a page reloads completely or the user navigates to another page, all previous element references become invalid. Even if the element visually reappears, Selenium considers its

4. DOM Changes via JavaScript or AJAX

Modern web applications frequently use JavaScript or AJAX to update content dynamically without a full page reload. If an element is re-rendered or replaced during these updates, the original WebElement reference becomes stale. Testers often encounter this when tables refresh automatically or form update fields dynamically.

5. Element Re-rendering

Frameworks like React, Angular, and Vue often re-render components in place. Even if the element appears unchanged, Selenium treats it as a new element because its internal ID or DOM node has been replaced. Interacting with the old reference triggers a stale exception.

6. Switching Between Frames or Windows

When switching frames or browser windows, WebElement references from the previous context become stale. Selenium cannot interact with elements outside the active frame or window. Testers must switch to the correct frame or window before performing operations.

7. Element Removed and Recreated

Some web applications remove an element and then immediately create a new one in the same location. This is common in dynamic modals or live search results. The new element may look identical, but Selenium cannot use the previous reference because it points to the old, removed node.

8. Issues with @CacheLookup in Page Object Model

Using @CacheLookup in Page Object Models can cause stale element exceptions on dynamic pages. This annotation stores a WebElement reference in memory, assuming it does not change. On pages where elements are frequently updated, caching references can result in stale exceptions. Removing @CacheLookup or using fresh lookups resolves the issue.

How to Spot a Stale Element Reference Exception

Detecting a Stale Element Reference Exception early is essential for maintaining stable Selenium scripts. This exception typically appears as soon as Selenium tries to interact with a WebElement that is no longer valid. Understanding its signs allows testers to troubleshoot efficiently and implement the right handling strategies.

Key indicators that a stale element exception has occurred include the following:

  • Immediate Exception on Interaction: Selenium throws a StaleElementReferenceException when executing methods like click(), sendKeys(), getText(), or isDisplayed() on an outdated element.
  • Intermittent Test Failures: Tests may pass sometimes and fail at other times if elements are dynamically updated. This is common in applications with AJAX content, auto-refreshing tables, or interactive forms.
  • Element Exists Visually but Fails in Selenium: A WebElement may appear on the page, but Selenium cannot interact with it because the DOM reference is no longer valid. This often confuses testers who assume the locator is incorrect.
  • Errors After Page Updates: Operations performed immediately after page reloads, dynamic content updates, or frame/window switches can trigger the exception.
  • Cached Elements in Page Object Models: If @CacheLookup is used in a Page Object Model, elements that are dynamically updated may become stale even though they exist visually on the page.

Techniques to Handle Stale Element Reference Exception

Selenium provides multiple approaches to handle stale element exceptions. Choosing the right strategy depends on the application’s behavior, page dynamics, and test requirements. Below are effective techniques with context and practical considerations:

1. Waiting Explicitly Using WebDriverWait

Dynamic pages often update elements after a short delay. Using explicit waits ensures Selenium interacts with elements only after they are present and stable in the DOM. For example, WebDriverWait can wait until an element is visible, clickable, or present in the DOM.

  • How it works: Selenium polls the DOM at regular intervals until the expected condition is met or a timeout occurs.
  • Example scenario: Waiting for a search result row to appear after an AJAX request.
  • Benefit: Reduces the risk of interacting with elements before they are re-rendered or replaced.

2. Using Try-Catch Blocks

Wrapping interactions in a try-catch block allows scripts to recover from stale element exceptions dynamically. Testers can attempt to locate the element again or retry the action.

  • How it works: When Selenium throws a StaleElementReferenceException, the catch block handles it and re-fetches the element from the DOM.
  • Example scenario: Clicking a button that is frequently replaced after page updates.
  • Benefit: Increases test stability for intermittent dynamic changes without failing the entire test.

3. Applying the Page Object Model Correctly

Proper use of the Page Object Model (POM) can reduce stale references. Avoid caching elements with @CacheLookup on pages where elements are dynamically updated. Instead, locate elements each time they are accessed.

  • How it works: Each method fetches the latest element from the DOM instead of relying on stored references.
  • Example scenario: Forms with dynamic validation messages or tables with auto-refreshing rows.
  • Benefit: Ensures Selenium interacts with the current version of the element and avoids stale references.

4. Refreshing the Web Page or Element

In some cases, refreshing the page or reloading a specific section ensures that Selenium interacts with fresh elements. This can be combined with waits to ensure elements are ready for interaction.

  • How it works: Use driver.navigate().refresh() or re-locate elements after an update.
  • Example scenario: A dashboard widget that reloads data periodically.
  • Benefit: Resets element references and eliminates stale exceptions for elements that are completely replaced.
  • Combining Techniques: Often, a combination of explicit waits, try-catch retries, and proper POM usage provides the most stable solution for dynamic web applications.

How Testing on Real Devices and Browsers Helps Identify Stale Element Issues

Testing Selenium scripts on real devices and browsers exposes dynamic behaviors that may not appear in local or simulated environments. Elements can behave differently due to variations in rendering engines, screen sizes, input methods, and network conditions. These differences often reveal stale element issues that are otherwise undetected.

Key points to consider:

  • Rendering Differences: An element may load faster or slower on a real device compared with a desktop browser. Timing differences can cause Selenium to interact with a stale element if waits are not correctly implemented.
  • Dynamic Updates on Mobile Browsers: Mobile browsers may trigger AJAX calls or re-render elements differently, leading to stale references in scripts that pass on desktop environments.
  • Frame and Window Handling: Switching between frames or pop-ups may behave differently on real browsers. Scripts that rely on cached references are more likely to fail.
  • Network Latency and Asynchronous Loading: Real-world network conditions can delay page updates. Explicit waits and retry mechanisms are essential to handle elements that update after AJAX requests.
  • Cross-Browser Behavior: Differences in Chrome, Firefox, Safari, or Edge can affect how the DOM updates. Testing across multiple browsers ensures that stale element handling works consistently.

Platforms like BrowserStack provide access to thousands of real devices and browsers, allow parallel test execution, and offer detailed logs, screenshots, and video recordings. This makes it easier to identify and resolve stale element exceptions, validate Selenium scripts across multiple environments, and ensure consistent test reliability without managing physical hardware.

Conclusion

A Stale Element Reference Exception occurs when Selenium tries to interact with an element that is no longer part of the current DOM. Testers can handle these exceptions effectively by using explicit waits, implementing try-catch retries, correctly applying the Page Object Model, and refreshing elements when necessary.

Testing on real devices and browsers ensures that these handling techniques work under real-world conditions, where rendering, network, and device variations can affect element stability. Use platforms like BrowserStack that allows executing Selenium tests across multiple real devices and browsers, and provides logs, screenshots, and videos for debugging.

Written by
Rohit Rajpal
Rohit Rajpal is a B2B Content Strategist at BrowserStack, helping SaaS brands build AI-first strategies that drive authority and revenue. He writes about content, strategy, and the future of search in the zero-click era.

Related posts