Skip to main content
SeleniumDecoded

Dropdowns and Select Elements

Learn to interact with HTML select elements, custom dropdowns, and autocomplete inputs.

Selenium 3 & 4 Stable

Dropdown menus come in different forms: native HTML select elements, custom JavaScript-powered dropdowns, and autocomplete inputs. Each requires different handling techniques.

Native Select Elements

Selenium provides a Select class specifically for handling HTML <select> elements.

Using the Select Class
Selenium 3 & 4 Stable
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
// Find the select element
WebElement selectElement = driver.findElement(By.id("country"));
Select dropdown = new Select(selectElement);
// Select by visible text (what user sees)
dropdown.selectByVisibleText("United States");
// Select by value attribute
dropdown.selectByValue("us");
// Select by index (0-based)
dropdown.selectByIndex(2);
// Get currently selected option
WebElement selected = dropdown.getFirstSelectedOption();
String selectedText = selected.getText();
System.out.println("Selected: " + selectedText);
// Get all available options
List<WebElement> allOptions = dropdown.getOptions();
for (WebElement option : allOptions) {
System.out.println(option.getText());
}
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
# Find the select element
select_element = driver.find_element(By.ID, "country")
dropdown = Select(select_element)
# Select by visible text (what user sees)
dropdown.select_by_visible_text("United States")
# Select by value attribute
dropdown.select_by_value("us")
# Select by index (0-based)
dropdown.select_by_index(2)
# Get currently selected option
selected = dropdown.first_selected_option
selected_text = selected.text
print(f"Selected: {selected_text}")
# Get all available options
all_options = dropdown.options
for option in all_options:
print(option.text)
// Note: JavaScript Selenium doesn't have a built-in Select class
// You need to work with the element directly or use helpers
const selectElement = await driver.findElement(By.id('country'));
// Select by visible text - click option with matching text
const options = await selectElement.findElements(By.tagName('option'));
for (const option of options) {
if (await option.getText() === 'United States') {
await option.click();
break;
}
}
// Select by value
await selectElement.findElement(By.css("option[value='us']")).click();
// Select by index
const allOptions = await selectElement.findElements(By.tagName('option'));
await allOptions[2].click();
// Get selected option
const selectedOption = await selectElement.findElement(By.css('option:checked'));
const selectedText = await selectedOption.getText();
console.log(`Selected: ${selectedText}`);
using OpenQA.Selenium.Support.UI;
// Find the select element
IWebElement selectElement = driver.FindElement(By.Id("country"));
SelectElement dropdown = new SelectElement(selectElement);
// Select by visible text (what user sees)
dropdown.SelectByText("United States");
// Select by value attribute
dropdown.SelectByValue("us");
// Select by index (0-based)
dropdown.SelectByIndex(2);
// Get currently selected option
IWebElement selected = dropdown.SelectedOption;
string selectedText = selected.Text;
Console.WriteLine($"Selected: {selectedText}");
// Get all available options
IList<IWebElement> allOptions = dropdown.Options;
foreach (IWebElement option in allOptions)
{
Console.WriteLine(option.Text);
}

Multi-Select Dropdowns

Some select elements allow multiple selections:

Multi-Select Handling
Selenium 3 & 4 Stable
Select multiSelect = new Select(driver.findElement(By.id("skills")));
// Check if multi-select is enabled
boolean isMultiple = multiSelect.isMultiple();
if (isMultiple) {
// Select multiple options
multiSelect.selectByVisibleText("Java");
multiSelect.selectByVisibleText("Python");
multiSelect.selectByValue("javascript");
// Get all selected options
List<WebElement> selectedOptions = multiSelect.getAllSelectedOptions();
System.out.println("Selected " + selectedOptions.size() + " items");
// Deselect specific option
multiSelect.deselectByVisibleText("Python");
// Deselect by value
multiSelect.deselectByValue("javascript");
// Deselect all
multiSelect.deselectAll();
}
multi_select = Select(driver.find_element(By.ID, "skills"))
# Check if multi-select is enabled
is_multiple = multi_select.is_multiple
if is_multiple:
# Select multiple options
multi_select.select_by_visible_text("Java")
multi_select.select_by_visible_text("Python")
multi_select.select_by_value("javascript")
# Get all selected options
selected_options = multi_select.all_selected_options
print(f"Selected {len(selected_options)} items")
# Deselect specific option
multi_select.deselect_by_visible_text("Python")
# Deselect by value
multi_select.deselect_by_value("javascript")
# Deselect all
multi_select.deselect_all()
const multiSelectElement = await driver.findElement(By.id('skills'));
const isMultiple = await multiSelectElement.getAttribute('multiple') !== null;
if (isMultiple) {
// Select multiple options (Ctrl+Click simulation not needed for select)
const options = await multiSelectElement.findElements(By.tagName('option'));
for (const option of options) {
const text = await option.getText();
if (['Java', 'Python', 'JavaScript'].includes(text)) {
await option.click();
}
}
// Get all selected options
const selectedOptions = await multiSelectElement.findElements(
By.css('option:checked')
);
console.log(`Selected ${selectedOptions.length} items`);
// Deselect by clicking again
for (const option of options) {
const text = await option.getText();
if (text === 'Python' && await option.isSelected()) {
await option.click();
}
}
}
SelectElement multiSelect = new SelectElement(driver.FindElement(By.Id("skills")));
// Check if multi-select is enabled
bool isMultiple = multiSelect.IsMultiple;
if (isMultiple)
{
// Select multiple options
multiSelect.SelectByText("Java");
multiSelect.SelectByText("Python");
multiSelect.SelectByValue("javascript");
// Get all selected options
IList<IWebElement> selectedOptions = multiSelect.AllSelectedOptions;
Console.WriteLine($"Selected {selectedOptions.Count} items");
// Deselect specific option
multiSelect.DeselectByText("Python");
// Deselect by value
multiSelect.DeselectByValue("javascript");
// Deselect all
multiSelect.DeselectAll();
}

Custom Dropdowns

Many modern websites use custom dropdowns built with divs and JavaScript. These require different handling:

Custom Dropdown Interaction
Selenium 3 & 4 Medium
// Step 1: Click the dropdown trigger to open it
WebElement dropdownTrigger = driver.findElement(By.className("dropdown-toggle"));
dropdownTrigger.click();
// Step 2: Wait for options to be visible
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.className("dropdown-menu")
));
// Step 3: Click the desired option
WebElement option = driver.findElement(
By.xpath("//div[@class='dropdown-menu']//span[text()='Option 2']")
);
option.click();
// Alternative: Use Actions for hover-activated dropdowns
Actions actions = new Actions(driver);
WebElement menu = driver.findElement(By.className("menu-item"));
actions.moveToElement(menu).perform();
// Wait and click submenu item
WebElement submenuItem = wait.until(ExpectedConditions.elementToBeClickable(
By.className("submenu-item")
));
submenuItem.click();
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
# Step 1: Click the dropdown trigger to open it
dropdown_trigger = driver.find_element(By.CLASS_NAME, "dropdown-toggle")
dropdown_trigger.click()
# Step 2: Wait for options to be visible
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located(
(By.CLASS_NAME, "dropdown-menu")
))
# Step 3: Click the desired option
option = driver.find_element(
By.XPATH, "//div[@class='dropdown-menu']//span[text()='Option 2']"
)
option.click()
# Alternative: Use Actions for hover-activated dropdowns
actions = ActionChains(driver)
menu = driver.find_element(By.CLASS_NAME, "menu-item")
actions.move_to_element(menu).perform()
# Wait and click submenu item
submenu_item = wait.until(EC.element_to_be_clickable(
(By.CLASS_NAME, "submenu-item")
))
submenu_item.click()
const { until, Actions } = require('selenium-webdriver');
// Step 1: Click the dropdown trigger to open it
const dropdownTrigger = await driver.findElement(By.className('dropdown-toggle'));
await dropdownTrigger.click();
// Step 2: Wait for options to be visible
await driver.wait(
until.elementLocated(By.className('dropdown-menu')),
10000
);
// Step 3: Click the desired option
const option = await driver.findElement(
By.xpath("//div[@class='dropdown-menu']//span[text()='Option 2']")
);
await option.click();
// Alternative: Use Actions for hover-activated dropdowns
const actions = driver.actions({ async: true });
const menu = await driver.findElement(By.className('menu-item'));
await actions.move({ origin: menu }).perform();
// Wait and click submenu item
const submenuItem = await driver.wait(
until.elementIsVisible(driver.findElement(By.className('submenu-item'))),
10000
);
await submenuItem.click();
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
// Step 1: Click the dropdown trigger to open it
IWebElement dropdownTrigger = driver.FindElement(By.ClassName("dropdown-toggle"));
dropdownTrigger.Click();
// Step 2: Wait for options to be visible
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(
By.ClassName("dropdown-menu")
));
// Step 3: Click the desired option
IWebElement option = driver.FindElement(
By.XPath("//div[@class='dropdown-menu']//span[text()='Option 2']")
);
option.Click();
// Alternative: Use Actions for hover-activated dropdowns
Actions actions = new Actions(driver);
IWebElement menu = driver.FindElement(By.ClassName("menu-item"));
actions.MoveToElement(menu).Perform();
// Wait and click submenu item
IWebElement submenuItem = wait.Until(ExpectedConditions.ElementToBeClickable(
By.ClassName("submenu-item")
));
submenuItem.Click();

Autocomplete/Typeahead Inputs

Autocomplete fields require typing to trigger suggestions:

Autocomplete Field Handling
Selenium 3 & 4 Medium
// Find the autocomplete input
WebElement searchInput = driver.findElement(By.id("city-search"));
// Clear and type to trigger suggestions
searchInput.clear();
searchInput.sendKeys("New Yo");
// Wait for suggestions to appear
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(
By.className("autocomplete-suggestions")
));
// Option 1: Click a specific suggestion
WebElement suggestion = driver.findElement(
By.xpath("//div[@class='autocomplete-item'][contains(text(), 'New York')]")
);
suggestion.click();
// Option 2: Use keyboard to select
searchInput.sendKeys(Keys.ARROW_DOWN); // Move to first suggestion
searchInput.sendKeys(Keys.ARROW_DOWN); // Move to second suggestion
searchInput.sendKeys(Keys.ENTER); // Select current suggestion
// Verify selection
String selectedValue = searchInput.getAttribute("value");
System.out.println("Selected: " + selectedValue);
# Find the autocomplete input
search_input = driver.find_element(By.ID, "city-search")
# Clear and type to trigger suggestions
search_input.clear()
search_input.send_keys("New Yo")
# Wait for suggestions to appear
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located(
(By.CLASS_NAME, "autocomplete-suggestions")
))
# Option 1: Click a specific suggestion
suggestion = driver.find_element(
By.XPATH, "//div[@class='autocomplete-item'][contains(text(), 'New York')]"
)
suggestion.click()
# Option 2: Use keyboard to select
search_input.send_keys(Keys.ARROW_DOWN) # Move to first suggestion
search_input.send_keys(Keys.ARROW_DOWN) # Move to second suggestion
search_input.send_keys(Keys.ENTER) # Select current suggestion
# Verify selection
selected_value = search_input.get_attribute("value")
print(f"Selected: {selected_value}")
// Find the autocomplete input
const searchInput = await driver.findElement(By.id('city-search'));
// Clear and type to trigger suggestions
await searchInput.clear();
await searchInput.sendKeys('New Yo');
// Wait for suggestions to appear
await driver.wait(
until.elementLocated(By.className('autocomplete-suggestions')),
10000
);
// Option 1: Click a specific suggestion
const suggestion = await driver.findElement(
By.xpath("//div[@class='autocomplete-item'][contains(text(), 'New York')]")
);
await suggestion.click();
// Option 2: Use keyboard to select
await searchInput.sendKeys(Key.ARROW_DOWN); // Move to first suggestion
await searchInput.sendKeys(Key.ARROW_DOWN); // Move to second suggestion
await searchInput.sendKeys(Key.ENTER); // Select current suggestion
// Verify selection
const selectedValue = await searchInput.getAttribute('value');
console.log(`Selected: ${selectedValue}`);
// Find the autocomplete input
IWebElement searchInput = driver.FindElement(By.Id("city-search"));
// Clear and type to trigger suggestions
searchInput.Clear();
searchInput.SendKeys("New Yo");
// Wait for suggestions to appear
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementIsVisible(
By.ClassName("autocomplete-suggestions")
));
// Option 1: Click a specific suggestion
IWebElement suggestion = driver.FindElement(
By.XPath("//div[@class='autocomplete-item'][contains(text(), 'New York')]")
);
suggestion.Click();
// Option 2: Use keyboard to select
searchInput.SendKeys(Keys.ArrowDown); // Move to first suggestion
searchInput.SendKeys(Keys.ArrowDown); // Move to second suggestion
searchInput.SendKeys(Keys.Enter); // Select current suggestion
// Verify selection
string selectedValue = searchInput.GetAttribute("value");
Console.WriteLine($"Selected: {selectedValue}");

Datepickers

Date pickers are often custom widgets requiring special handling:

Date Picker Handling
Selenium 3 & 4 Medium
// Method 1: Direct input (if allowed)
WebElement dateInput = driver.findElement(By.id("date-field"));
dateInput.clear();
dateInput.sendKeys("12/25/2024");
// Method 2: Use JavaScript to set value (bypasses validation)
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(
"arguments[0].value = '2024-12-25'", dateInput
);
// Method 3: Interact with calendar widget
WebElement dateField = driver.findElement(By.id("date-picker"));
dateField.click(); // Opens calendar
// Navigate to correct month/year
WebElement nextMonth = driver.findElement(By.className("next-month"));
nextMonth.click();
// Select the day
WebElement day = driver.findElement(
By.xpath("//td[@data-date='25' and not(contains(@class, 'disabled'))]")
);
day.click();
# Method 1: Direct input (if allowed)
date_input = driver.find_element(By.ID, "date-field")
date_input.clear()
date_input.send_keys("12/25/2024")
# Method 2: Use JavaScript to set value (bypasses validation)
driver.execute_script(
"arguments[0].value = '2024-12-25'", date_input
)
# Method 3: Interact with calendar widget
date_field = driver.find_element(By.ID, "date-picker")
date_field.click() # Opens calendar
# Navigate to correct month/year
next_month = driver.find_element(By.CLASS_NAME, "next-month")
next_month.click()
# Select the day
day = driver.find_element(
By.XPATH, "//td[@data-date='25' and not(contains(@class, 'disabled'))]"
)
day.click()
// Method 1: Direct input (if allowed)
const dateInput = await driver.findElement(By.id('date-field'));
await dateInput.clear();
await dateInput.sendKeys('12/25/2024');
// Method 2: Use JavaScript to set value (bypasses validation)
await driver.executeScript(
"arguments[0].value = '2024-12-25'", dateInput
);
// Method 3: Interact with calendar widget
const dateField = await driver.findElement(By.id('date-picker'));
await dateField.click(); // Opens calendar
// Navigate to correct month/year
const nextMonth = await driver.findElement(By.className('next-month'));
await nextMonth.click();
// Select the day
const day = await driver.findElement(
By.xpath("//td[@data-date='25' and not(contains(@class, 'disabled'))]")
);
await day.click();
// Method 1: Direct input (if allowed)
IWebElement dateInput = driver.FindElement(By.Id("date-field"));
dateInput.Clear();
dateInput.SendKeys("12/25/2024");
// Method 2: Use JavaScript to set value (bypasses validation)
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript(
"arguments[0].value = '2024-12-25'", dateInput
);
// Method 3: Interact with calendar widget
IWebElement dateField = driver.FindElement(By.Id("date-picker"));
dateField.Click(); // Opens calendar
// Navigate to correct month/year
IWebElement nextMonth = driver.FindElement(By.ClassName("next-month"));
nextMonth.Click();
// Select the day
IWebElement day = driver.FindElement(
By.XPath("//td[@data-date='25' and not(contains(@class, 'disabled'))]")
);
day.Click();

Common Dropdown Patterns

TypeRecognitionApproach
Native <select>Has <option> childrenUse Select class
Button dropdownDiv/button opens menuClick trigger, then option
AutocompleteInput shows suggestionsType, wait, select
Hover menuOpens on mouse hoverUse Actions.moveToElement

Best Practices

  1. Identify dropdown type before writing code
  2. Use explicit waits for options to appear
  3. Verify selection after making it
  4. Handle timing - dropdowns often have animations
  5. Consider keyboard navigation as fallback

Next Steps