</>

Technology

Selenium

Difficulty

Beginner

Interview Question

How to handle dropdowns in Selenium?

Use the Select class from Selenium to interact with HTML <select> dropdowns by visible text, value, or index.

Answer

Use the Select class from org.openqa.selenium.support.ui to handle native HTML <select> dropdowns.

Setup:

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

Select dropdown = new Select(driver.findElement(By.id("countries")));

Select by visible text:

Java
dropdown.selectByVisibleText("India");

Select by index (starts from 0):

Java
dropdown.selectByIndex(1);

Select by value attribute:

Java
dropdown.selectByValue("Ind");

Get all options:

Java
List<WebElement> options = dropdown.getOptions();
for (WebElement opt : options) {
    System.out.println(opt.getText());
}

Multi-select dropdown:

Java
if (dropdown.isMultiple()) {
    dropdown.selectByVisibleText("India");
    dropdown.selectByVisibleText("USA");
    dropdown.deselectAll();
}

Important: Select class works ONLY with native HTML <select> elements. For custom dropdowns built with React, Angular, or Material UI — click the dropdown trigger and then click the option directly using findElement().

Follow AutomateQA

Related Topics