Q8 of 37 · Selenium

How do you handle a dropdown in Selenium WebDriver?

SeleniumJuniorseleniumdropdownselectfundamentals

Short answer

Short answer: For native `<select>`, wrap the element in `Select` and use `selectByVisibleText`, `selectByValue`, or `selectByIndex`. For custom dropdowns (divs, ARIA listbox, autocomplete), Select doesn't apply — click to open, then click the option.

Detail

Selenium has two completely different paths depending on whether the dropdown is a real <select> or a custom widget — and confusing them is the most common bug.

Native <select> — the HTML element. Wrap it in Selenium's Select helper:

Select country = new Select(driver.findElement(By.id("country")));
country.selectByVisibleText("United Kingdom");
country.selectByValue("GB");
country.selectByIndex(2);

Select also exposes getOptions(), getFirstSelectedOption(), and (for multi-selects) deselectAll().

Custom dropdowns — anything built with <div> / <ul> / Material UI / React Select / autocomplete combobox. Select will throw UnexpectedTagNameException because the root isn't a <select>. The handling is browser-as-user:

  1. Click the trigger to open the dropdown.
  2. Wait for the option list to render (often a portal mounted to <body>).
  3. Click the desired option.
  4. (For autocomplete) Type the search text first, then click the suggestion.
driver.findElement(By.cssSelector("[data-test=country-dropdown]")).click();
new WebDriverWait(driver, Duration.ofSeconds(5))
    .until(ExpectedConditions.elementToBeClickable(
        By.xpath("//li[@role='option' and text()='United Kingdom']")
    ))
    .click();

The interview signal: knowing Select only works on <select> and instinctively reaching for click-and-pick for everything else.

// WHAT INTERVIEWERS LOOK FOR

Distinguishing native vs custom dropdowns. Knowing Select's three select-by methods. Recognising autocomplete/portal-rendered options as a separate flavour.

// COMMON PITFALL

Trying to wrap a custom dropdown in Select and getting UnexpectedTagNameException, or failing to wait for a portal-rendered option list before clicking.