Handling Ajax Dropdowns in Selenium
Ajax dropdowns load their options dynamically from a server after an initial selection or user action. The dropdown options aren''t in the DOM at page load — they appear asynchronously after an API call.
The problem:
// This fails — options not loaded yet after Ajax call
driver.findElement(By.id("country")).click();
List<WebElement> options = driver.findElements(By.cssSelector("#city option"));
// options.size() = 0 because Ajax hasn't finished
Solution 1 — Explicit Wait (WebDriverWait):
// Click the first dropdown to trigger Ajax
driver.findElement(By.id("country")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
// Wait for second dropdown to populate
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("city")));
wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(
By.cssSelector("#city option"), 1
));
// Now interact with the loaded options
Select cityDropdown = new Select(driver.findElement(By.id("city")));
cityDropdown.selectByVisibleText("Mumbai");
Solution 2 — Wait for dropdown to be populated:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait until city has more than 1 option (default "Select City" + actual options)
wait.until(driver -> {
Select sel = new Select(driver.findElement(By.id("city")));
return sel.getOptions().size() > 1;
});
Select citySelect = new Select(driver.findElement(By.id("city")));
citySelect.selectByVisibleText("Delhi");
Solution 3 — FluentWait with custom polling:
FluentWait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofMillis(500))
.ignoring(StaleElementReferenceException.class);
WebElement cityDropdown = fluentWait.until(
ExpectedConditions.elementToBeClickable(By.id("city"))
);
new Select(cityDropdown).selectByIndex(2);
Solution 4 — ImplicitWait (global fallback):
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
// All findElement calls wait up to 10s for element to appear
When each wait suits Ajax dropdowns:
| Wait Type | Best for |
|---|---|
WebDriverWait | Known element condition (visibility, clickable) |
FluentWait | Custom condition with custom polling interval |
ImplicitWait | Simple delays before element appears in DOM |
Key point: Use Selenium sync commands — ImplicitWait, WebDriverWait, or FluentWait — to handle the delay between triggering the Ajax call and the dropdown options becoming available.
