How to handle dropdown in selenium with java

In Selenium, dropdowns can be handled easily using the Select class in Java.
Once you create a Select object from a dropdown WebElement, you can interact with its options using three main methods:

  • selectByValue(String value) – Selects the option by its HTML value attribute.
  • selectByIndex(int index) – Selects the option based on its position (0-based index).
  • selectByVisibleText(String text) – Selects the option by the text visible to the user.

1. Handle dropdown with selectByValue

This method selects an option by matching its value attribute:

dropdown.selectByValue("opt3");

2. Handle dropdown with selectByIndex

This method selects an option by its position (index starts from 0):

dropdown.selectByIndex(2);

3. Handle dropdown with selectByVisibleText

This method selects an option by matching the exact visible text:

dropdown.selectByVisibleText("Option 1");

Complete Example:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;

public class SampleTest {

    @Test
    public void handleDropdown() {
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");
        driver.manage().window().maximize();

        // Locate the dropdown element
        WebElement dropdownElement = driver.findElement(By.id("myDropdown"));

        // Create a Select object
        Select dropdown = new Select(dropdownElement);

        // 1. Select by visible text
        dropdown.selectByVisibleText("Option 1");

        // 2. Select by index
        dropdown.selectByIndex(2);

        // 3. Select by value
        dropdown.selectByValue("opt3");

        driver.quit();
    }
}

Select First Option in Dropdown

You can get the currently selected option using getFirstSelectedOption():

WebElement selectedOption = dropdown.getFirstSelectedOption();
System.out.println("Selected: " + selectedOption.getText());

Get All Options from Dropdown

You can fetch and print all available options with getOptions():

List<WebElement> allOptions = dropdown.getOptions();
for (WebElement option : allOptions) {
    System.out.println(option.getText());
}

This way, you can identify, select, and extract dropdown values effectively using Selenium with Java.

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Testingtalkslatest.com - A project by CreativeHub IT Solutions.
Contact Us At: support@testingtalkslatest.com
Our Partner websites - Classified Hub , CodesToolbox , Smart Fitness Guide , CodesToolbox , Testing Forum
Scroll to Top
0
Would love your thoughts, please comment.x
()
x