Handling Dropdowns

RecipeBox's Add Recipe form has a categoryDropdown — a real HTML <select> element with options like "Breakfast", "Main Course", and "Dessert". Clicking a <select> directly with click() just opens it; Selenium gives you a dedicated helper, the Select class, for actually choosing an option.

The Select Class

Import it, then wrap it around the <select> WebElement:

import org.openqa.selenium.support.ui.Select;

WebElement dropdownElement = driver.findElement(By.id("categoryDropdown"));
Select categoryDropdown = new Select(dropdownElement);
Note: Select only works on genuine <select><option>...</select> markup. Passing any other element to its constructor throws an UnexpectedTagNameException.

selectByVisibleText()

The most readable and most commonly used option — matches the text the user actually sees in the dropdown.

categoryDropdown.selectByVisibleText("Main Course");

selectByValue()

Matches the underlying value attribute of the <option> tag, which may differ from its visible text (e.g. <option value="main">Main Course</option>).

categoryDropdown.selectByValue("main");

selectByIndex()

Selects by position, zero-based. Fragile if options get reordered, but occasionally useful for "just pick something" scenarios.

// Selects the 2nd option in the list (index 0 is the 1st)
categoryDropdown.selectByIndex(1);

Reading the Currently Selected Option

categoryDropdown.selectByVisibleText("Dessert");

WebElement selectedOption = categoryDropdown.getFirstSelectedOption();
System.out.println("Currently selected: " + selectedOption.getText());

// If the dropdown allows multiple selections, use getAllSelectedOptions() instead
List<WebElement> selectedOptions = categoryDropdown.getAllSelectedOptions();

Full Example: Category Selection in Add Recipe

driver.findElement(By.id("recipeTitle")).sendKeys("Paneer Butter Masala");

Select categoryDropdown = new Select(driver.findElement(By.id("categoryDropdown")));
categoryDropdown.selectByVisibleText("Main Course");

System.out.println("Category set to: " + categoryDropdown.getFirstSelectedOption().getText());

driver.findElement(By.id("saveRecipeBtn")).click();

Custom (Non-<select>) Dropdowns

Important: Plenty of modern UI kits build their own dropdown widgets out of a <div> that shows/hides a list of <li> items on click, styled to look like a native dropdown. These are not <select> elements — the Select class doesn't apply to them at all. For those, treat it like any other click sequence: click the widget to open it, then click the specific option element.
// A hypothetical custom JS dropdown, not a real <select>
driver.findElement(By.id("customCategoryDropdown")).click();
driver.findElement(By.xpath("//li[text()='Main Course']")).click();
Next: Deleting a recipe pops up a native JS confirm dialog. See how to handle it in Handling Alerts & Popups.