πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 8 of 100
Synchronization
Intermediate

Selecting Dynamically Loaded AJAX Dropdown Options

πŸ“‹Scenario Overview

Selecting Dynamically Loaded AJAX Dropdown Options

Key Takeaways & Cheat Sheet

  • βœ“Trigger dropdown options load by clicking the wrapper first
  • βœ“Avoid Selenium Select class on custom React/Angular divs or lists
  • βœ“Use visibilityOfAllElementsLocatedBy to wait for dynamic elements
  • βœ“Iterate option lists dynamically to click matching target text value

Short Direct Answer

Modern web applications use custom styling tags (like div, ul, li) to render dropdowns, fetching data dynamically via AJAX only after the user clicks the field. Standard Select commands do not work here. You must first click the container to trigger the API, explicitly wait for option elements to be visible, and click the option matching your text.

⚠️ Senior Warning (Red Flag)

Never use the Select helper class on custom divs or ul/li list containers. The Select class only works with standard HTML <select> tags, throwing an UnexpectedTagNameException if applied elsewhere.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Always wait for the visibility of the options list, not just presence in DOM. If you attempt to click an option that is present but hidden, Selenium will throw an ElementNotInteractableException.

SeleniumAutomation.java
Selenium 4 + Java
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.util.List;

public void selectDynamicAjaxOption(By dropdownHost, By optionLocator, String targetText) {
    // 1. Click dropdown to open and trigger AJAX network request
    driver.findElement(dropdownHost).click();

    // 2. Wait explicitly until dropdown options list becomes visible
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    List<WebElement> options = wait.until(
        ExpectedConditions.visibilityOfAllElementsLocatedBy(optionLocator)
    );

    // 3. Dynamic selection loop
    for (WebElement option : options) {
        if (option.getText().trim().equalsIgnoreCase(targetText)) {
            option.click();
            return;
        }
    }
    throw new NoSuchElementException("Failed to find dynamic option: " + targetText);
}