How to Select Value & Handle Dropdown in Selenium without Select Class

Test Dropdown without Select Class in Selenium in real user conditions on real device cloud

Get Started free
Guide Banner Image
Home Guide How to Select Value & Handle Dropdown in Selenium without Select Class

How to Select Value & Handle Dropdown in Selenium without Select Class

UI elements are vital for any website. It is the UI of the website which the user interacts with, and hence it is crucial to ensure that the UI is user friendly for a seamless user experience. UI testing ensures that all the UI elements of the website are functioning as expected.

A website consists of several UI elements such as forms, text-fields, frames, iframes, radio buttons, check boxes, dropdowns etc. Drop downs are used mostly in web forms, to single or multi select values from it. And to select drop down options via automation, Selenium is one of most widely used automation libraries to automate websites.

Dropdown in Selenium

Drop downs in a website could be created in several different ways. Some dropdowns are created using <select> HTML tag and some others are created using <ul> ,<li>, <button> and <div> tags.

Some dropdowns are dynamic in nature which means after clicking or selecting any option, the drop downs values would populate accordingly. And in some cases, you need to mouse hover on an element in Selenium to see the drop-down options.

Selenium WebDriver provides Select class which can be used only for drop down created using <select> HTML tag. Select class has methods such as selectByVisibleText(), selectByIndex() and selectByValue() to select the desired option from dropdown.

However, for NonSelect dropdowns, Select class cannot be used. There should be a common way to handle different types of dropdown through Selenium Automation.

This tutorial explores How to Select Values in Dropdown in Selenium without using Select Class.

How to Select Dropdown in Selenium?

You can handle dropdown in Selenium using Select Class and without using Select Class. Below are 5 different methods that can be used to select value in dropdown in Selenium without using Select Class. These methods are:

  1. By storing all the options in List and iterating through it
  2. By creating Custom Locator and without iterating the List
  3. By using JavaScriptExecutor class
  4. By using sendKeys
  5. By using Actions Class

Pre-requisites for handling dropdown in Selenium without using Select Class

  • Java version 8 or higher installed on the system.
  • Java editor for writing the Selenium with Java code.
  • For a Maven add the Selenium Java dependency in pom.xml file

(Note: Need Selenium 4 and Above)

<dependency>

<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>4.6.0</version>

</dependency>

Different Methods to handle Dropdown in Selenium without using Select Class

Dropdown in Selenium can be handled using different methods, let us understand how these different methods helps to handle dropdown in Selenium.

Method 1: By storing all the options in List and iterating through it

You can handle Dropdown in Selenium by storing all the options in the form of a List and then iterate through it as seen in the example below:

Example:

Step 1 Launch BStackDemo website and click on the Order By drop down to make all the options visible.

 driver.get("https://www.bstackdemo.com/");

 driver.findElement(By.xpath("//select")).click();

Handling Dropdown in Selenium without using Select Class by storing all the options in List and iterating through it

Step 2: Store all the options as WebElements in a List.

List<WebElement> allOptions=driver.findElements(By.cssSelector("select option"));

Step 3: Iterate the list using a for loop and click the desired option.

String option="Highest to lowest";

         for(int i=0; i<allOptions.size(); i++) {

            if(allOptions.get(i).getText().contains(option)) {

                     allOptions.get(i).click();

                     System.out.println("clicked");

                     break;

               }

         }

Step 4: Instead of for loop, enhanced for loop can only be used in the following way.

for(WebElement el:allOptions) {

              if(el.getText().contains(option)) {

                    el.click();

              }

  }

Run Selenium Tests on Real Devices

Complete Code: 

public class SelectUsingList {

   @Test

   public void selectByList() {

         WebDriver driver = new ChromeDriver();

         driver.get("https://www.bstackdemo.com/");

      driver.findElement(By.xpath("//select")).click();

         List<WebElement> allOptions = driver.findElements(By.cssSelector("select option"));

         String option = "Highest to lowest";

         // Iterate the list using for loop

         for (int i = 0; i < allOptions.size(); i++) {

               if (allOptions.get(i).getText().contains(option)) {

                     allOptions.get(i).click();

                     System.out.println("clicked");

                     break;

               }

         }

   }

}

@AfterTest

public void tearDown(){

driver.quit();

}

Method 2: By creating Custom Locator and without iterating the List

In this method, you have to create custom Locator in Selenium, and then handle the drop down without iterating the List as seen in the example below:

BrowserStack Automate Banner 8

Example:

Step 1: Launch BStackDemo website and click on the Order By drop down to make all the options visible.

driver.get("https://www.bstackdemo.com/");

driver.findElement(By.xpath("//select")).click();

Step 2: Create a WebElement of the option to be selected from Drop down and click on it.

String option="Highest to lowest";

         WebElement dropdown =driver.findElement(By.xpath("//select/option[contains(text(), '"+option+"')]"));

dropdown.click();

Complete Code:

public class SelectUsingCustom {  

   @Test

   public void list() {

         WebDriver driver = new ChromeDriver();

         driver.get("https://www.bstackdemo.com/");

      driver.findElement(By.xpath("//select")).click();

         String option = "Highest to lowest";

         WebElement dropdown = driver.findElement(By.xpath("//select/option[contains(text(), '" + option + "')]"));

         dropdown.click();

         System.out.println("clicked");

   }

}

@AfterTest

public void tearDown(){

driver.quit();

}

In the above code, as it is not iterating the list of options, and using a custom WebElement, execution time would decrease.

Method 3: By using JavaScriptExecutor class

JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium WebDriver. You can use the executeScript method of JavaScriptExecutor interface to select an option from the drop down by using the value property of the element as seen in the example below:

Run Selenium Tests on Real Devices

Example:

Step 1: Launch BStackDemo website and create a WebElement for the Order By dropdown.

driver.get("https://www.bstackdemo.com/");

WebElement dd=driver.findElement(By.xpath("//select"));

Step 2: Use executeScript method to select the desired option.

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("arguments[0].value='highestprice'", dd);

Handling Dropdown in Selenium without using Select Class by using JavaScriptExecutor class

Complete Code:

public class SelectUsingJavaScript { 

   WebDriver driver;

 

   @Test

   public void list() {

         WebDriver driver = new ChromeDriver();

         driver.get("https://www.bstackdemo.com/");

         WebElement dd = driver.findElement(By.xpath("//select"));

         JavascriptExecutor js = (JavascriptExecutor) driver;

   js.executeScript("arguments[0].value='highestprice'", dd);

   }

}

Method 4: By using sendKeys method

You can use sendKeys() method to select an option from a drop down by passing the element’s value as sendKeys char sequence as seen in the example below:

Example:

Step 1: Launch BStackDemo website and select the desired option by using sendKeys() method.

 driver.get("https://www.bstackdemo.com/");     

 driver.findElement(By.xpath("//select")).sendKeys("highestprice");

Complete Code:

public class SelectUsingSendkeys { 

   WebDriver driver;

 

   @Test

   public void list() {

         WebDriver driver = new ChromeDriver();

         driver.get("https://www.bstackdemo.com/");        

   driver.findElement(By.xpath("//select")).sendKeys("highestprice");        

   }

}

Try Selenium Testing on Real Devices

Method 5: By using Actions Class

Some drop-downs need to be hovered to display all the options present in it and then click on it. Actions class of Selenium is used for handling keyboard and mouse events as seen below:

Example:

Step 1: Launch the BrowserStack website and hover on the “Developers” menu from headers.

driver.get("https://www.browserstack.com/");

WebElement dd = driver.findElement(By.xpath("//span[@class='nav_item_name' and contains(text(), 'Developers')]"));

Actions action=new Actions(driver);

action.moveToElement(dd).perform();

Step 2: Create a custom web element of the option to be selected and click on it.

String option="Support";

         WebElement customOption=driver.findElement(By.xpath("//li[@class='developers-menu-control']/a[contains(text(), '"+option+"')]"));

         customOption.click();

Complete Code:

public class SelectHover { 

   WebDriver driver;

 

   @Test

   public void list() {

         WebDriver driver = new ChromeDriver();

         driver.get("https://www.browserstack.com/");

         WebElement dd = driver.findElement(By.xpath("//span[@class='nav_item_name' and contains(text(), 'Developers')]"));

         Actions action=new Actions(driver);

         action.moveToElement(dd).perform();

         String option="Support";

         WebElement customOption=driver.findElement(By.xpath("//li[@class='developers-menu-control']/a[contains(text(), '"+option+"')]"));

         customOption.click();

   }

}

Handling Selenium Dropdown Tests on Real Devices

The different methods of Handling Dropdowns in Selenium without Select Class as discussed in the previous sections can be run on real devices and browsers using BrowserStack Automate.

Run Selenium Tests on Real Devices

One of the key benefits of running the tests on real device cloud is the ability to execute tests under real user conditions which improves the overall accuracy of the code. Using BrowserStack Automate you can test the drop down functionality across 3000+ different real browser and device combinations.

Steps to automate using BrowserStack Automate Platform:

1. Sign up on BrowserStack Automate. Note the User Name and Access Key Password.

2. Navigate to Capabilities Generator page to select from a comprehensive set of options. Capabilities are a series of key-value pairs that allow you to configure your Selenium tests on the BrowserStack Cloud Selenium Grid.

3. In the below example, Android Samsung Galaxy S22 with OS version 12 and Chrome browser are selected.

Adding Desired Capabilities to Handle Dropdown in Selenium on Real Devices

4. In any java editor, create a Maven project and add Selenium Java, and TestNG dependencies.

<dependencies>

<dependency>

<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>4.5.0</version>

</dependency>




<dependency>

<groupId>org.testng</groupId>

<artifactId>testng</artifactId>

<version>7.6.1</version>

<scope>compile</scope>

</dependency>

</dependencies>

Talk to an Expert

5. Below code snippet showcases the demonstration of the first program (Store web elements in a list and iterate through it) using Automate Platform.

public class SelectUsingList {

    public static String username = "<browserstack username>";

    public static String accesskey = "<browserstack password>";

    public static final String URL = "https://" + username + ":" + accesskey + "@hub-cloud.browserstack.com/wd/hub";

    WebDriver driver;

    String url = "https://www.bstackdemo.com/";

    MutableCapabilities capabilities = new MutableCapabilities();

    HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();




    @BeforeTest

    public void setUp() throws MalformedURLException, InterruptedException {

     browserstackOptions.put("browserName", "chrome");

     browserstackOptions.put("deviceName", "Samsung Galaxy S22");

     browserstackOptions.put("realMobile", "true");

     browserstackOptions.put("osVersion", "12");

     capabilities.setCapability("bstack:options", browserstackOptions);

     driver = new RemoteWebDriver(new URL(URL), capabilities);

     driver.get(url);

     Thread.sleep(3000);




    }

    @Test

    public void selectByList() {    

     driver.findElement(By.xpath("//select")).click();

     List<WebElement> allOptions = driver.findElements(By.cssSelector("select option"));

     String option = "Highest to lowest";

     // Iterate the list using for loop

     for (int i = 0; i < allOptions.size(); i++) {

     if (allOptions.get(i).getText().contains(option)) {

     allOptions.get(i).click();

     System.out.println("clicked");

     break;

     }

     }

    }




@AfterTest

public void tearDown(){

driver.quit();

}

}

6. Run the program and observe the execution result on the Automate dashboard.

How to Select Value & Handle Dropdown in Selenium without Select Class

At times it may get tricky to select a drop-down value using Select Class in Selenium, hence we explored the different ways to automate drop down using Selenium without Select Class. However, it is important to run Selenium tests on different real devices and browser combinations to achieve cross device and cross browser compatibility with utmost accuracy.

BrowserStack offers a cloud Selenium Grid of 3000+ real browsers and devices for testing purposes. Simply sign up, choose the required device-browser-OS combination from 3000+ Desktop and Mobile browsers for Selenium Testing, and start testing websites for free.

Try BrowserStack for Free

Tags
Automated UI Testing Selenium Selenium Webdriver