Handling Dynamic Dropdown in Selenium

Profile picture for user arilio666

In this article, we will handle dynamic dropdowns, or we can call them dropdowns without a select tag. We can handle select tag dropdowns easily using the select class available in selenium.

  • This site right here has a different thing. It has no select tag. Then how do we handle them?
  • We can handle them using three methods.

1.) Using Direct Text Locator

  • We can use the XPath text locator and isolate the country we want to select.
  • Using this xpath for this site, we can isolate the country Maldives and select it.
        ChromeDriver driver = new ChromeDriver();
  • Likewise, we can change the country in the text field with the country we want to select and the selenium we choose them.

2.) Using For Loop.

  • Using for loop, we can get the list of elements from the countries available and iterate it.
int countryList = driver.findElements(By.xpath("//div[@role='combobox']")).size();
  • Get the size of the common webelement from countries isolated.
    for (int i = 0; i < countryList; i++) {
            String countryText = driver.findElements(By.xpath("//div[@role='combobox']")).get(i).getText();
            if (countryText.contains("Maldives")) {
  • By passing the countryList within the for-loop, we can get the index 'i' and get the text out of them.
  • Here we can see the countries it got from the for loop in the console.
  • Simply after that, with the help of the if statement, we can use contains and click the element.

3.) Advanced For Loop.

This is the easiest method and far more straightforward than for loop.

        List<WebElement> countryList = driver.findElements(By.xpath("//div[@role='combobox']"));

Here is the list of webelements we are going to iterate using foreach.

        for (WebElement ele : countryList) {
            if (ele.getText().contains("Angola")) {

For each, immediately create object ele, and using ele, we can get the text same as for loop and use contains inside if statement and fetch the element.