Selenium + Java · Lesson 26 of 44

0/44 done

Module 26: Handling Dynamic Web Elements

26. Handling Dynamic AJAX Elements & StaleElementReferenceException

16 minlesson

Your task

Implement waitForSpinnerToDisappear:

  1. Accept WebDriver driver and By spinnerLocator.
  2. Return new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.invisibilityOfElementLocated(spinnerLocator)).

Write it in the editor, then press Check answer (Ctrl + Enter).

Handling Spinners & Dynamic DOMs

java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));

// 1. Wait for loading spinner to disappear:
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".loading-spinner")));

// 2. Retry loop for StaleElementReferenceException:
public static void clickWithStaleRetry(WebDriver driver, By locator, int maxRetries) {
    int attempts = 0;
    while (attempts < maxRetries) {
        try {
            driver.findElement(locator).click();
            return;
        } catch (StaleElementReferenceException e) {
            attempts++;
        }
    }
    throw new RuntimeException("Element remained stale after " + maxRetries + " attempts: " + locator);
}

Key Takeaways & Walkthrough Summary

Single-page applications dynamically replace DOM elements upon data loading, triggering StaleElementReferenceException. In this lesson, you will master handling dynamic IDs, spinner disappearances, and robust retry patterns for stale elements. Let's tackle dynamic elements!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What causes StaleElementReferenceException?

The element reference was found in memory, but a JavaScript rerender removed or replaced the node in the DOM. Re-querying the locator solves it.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip