Selenium · Browser automation foundations
How do you select options in a dropdown?
Short answer
Wrap a native select element in the Select class and use selectByVisibleText, selectByValue or selectByIndex. For custom div-based dropdowns, click the trigger and then click the option like any other element.
The Select class only works with an actual select element. Many modern applications build dropdowns from divs and ARIA roles, so the same class will throw UnexpectedTagNameException. Inspect the DOM before choosing an approach.
Select country = new Select(driver.findElement(By.id("country")));
country.selectByVisibleText("India");
country.selectByValue("in");
country.selectByIndex(0);
Assert.assertEquals(country.getFirstSelectedOption().getText(), "India");
Select toppings = new Select(driver.findElement(By.id("toppings")));
toppings.selectByVisibleText("Cheese");
toppings.selectByVisibleText("Olives");
toppings.deselectByVisibleText("Cheese");- selectByVisibleText matches the rendered option text
- selectByValue matches the value attribute, not the label
- selectByIndex is zero-based and breaks if option order changes
- isMultiple reports whether the select allows multiple selections
- getOptions returns all options for assertions or dynamic selection
- Custom dropdowns need a click on the trigger, a wait for the listbox, then a click on the option
For a custom dropdown, assert the selected state through the accessible value or visible label, not through a CSS class that the design system may rename. If the widget opens a listbox in a portal, the options may be outside the dropdown container.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens if you use Select on a div-based dropdown?
- 2When would selectByIndex be a bad choice?
- 3How do you handle a multi-select?
- 4How do you test a custom ARIA combobox?
Say it in the interview
For a native select I use the Select class and prefer visible text or value over index, because index breaks when options reorder. For a custom div-based dropdown, Select does not apply; I click the trigger, wait for the listbox and click the option. I assert the visible selected value or accessible state rather than an internal CSS class. I only use keyboard navigation when accessibility behaviour is what the test is covering.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Selenium mock interview and get scored feedback on depth, clarity and confidence.