The <select> tag is a common control element for web forms, used for input fields where only a handful of options are valid. In Selenium WebDriver, select elements are handled using the unique "Select" class.
<select id="myDropdown">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Above is an example drop-down list which displays four different options. In order to interact with this element, we need to first tell WebDriver to identify it, we're going to save this in a variable defined as "mySelectElement."
var mySelectElement = driver.findElement(By.id("myDropdown"));
Now, in order to interact with the menu's different options, let's pass this element as a constructor to the Select class and define the resulting object as "myMenuObj."
var myMenuObj = new Select(mySelectElement);
You can also pass the WebDriver method directly into the class.
var myMenuObj = new Select(driver.findElement(By.id("myDropdown")));
Now that we've constructed the Select object with an associated element, we have a handful of different methods to interact with the menu's options. The available options are: selectByIndex, selectByValue and selectByVisible. Let's say we want to select "Mercedes."
myMenuObj.selectByIndex(2);
The selectByIndex method chooses an option with accordance to it's position in the list. With our example, from top top to bottom, the indices are 0-3, 0 being "Volvo" and 3 being "Audi." The options in between, Saab and Mercedes, are indices 1 and 2 respectively.
myMenuObj.selectByValue("mercedes");
selectByValue uses the "value" attribute of the option element. In this case, the value Mercedes is "mercedes."
myMenuObj.selectByVisibleText("Mercedes");
The visible text of the option is what falls between <option> and </option>, or what's displayed on the actual page.
Selenium HQ's documentation for the Select class can be found here. For our WebDriver documentation, click here.