</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How do you handle Ajax dropdowns in Selenium?

Use Selenium sync commands — ImplicitWait, WebDriverWait (explicit wait), or FluentWait — to wait for Ajax dropdown options to load before interacting.

Answer

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:

Java
// 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):

Java
// 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:

Java
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:

Java
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):

Java
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 TypeBest for
WebDriverWaitKnown element condition (visibility, clickable)
FluentWaitCustom condition with custom polling interval
ImplicitWaitSimple 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.

Follow AutomateQA

Related Topics