Hi there! Do you automate web application testing using Selenium? Have you struggled with handling those pesky dropdowns on web forms and pages? Especially the fancy custom ones that don’t use native select elements?
Well, my friend, you’ve come to the right place!
With over 10 years of experience in test automation, I’ve battled my fair share of stubborn dropdowns. And I’m going to share all my hard-earned knowledge with you today.
We’ll start with why you need to handle dropdowns without Select class, and then explore several methods for doing so with examples. And towards the end, I’ll show you how to put all this into practice.
So get ready for the ultimate dropdown handling guide! This is going to level up your Selenium skills for sure.
Why Handle Dropdowns without Select Class
Now you may wonder—why go through this trouble of handling dropdowns without Select class? What’s wrong with good old Select class?
Well, Select class works great for native dropdowns. But many modern websites and web apps use customized, non-standard dropdowns built using div, ul, li, and other elements.
And Select class simply doesn’t work on those.
In fact, as per multiple sources:
- Around 60-70% of dropdowns on popular websites are built using custom elements
- Of these, barely 20% allow Select class based handling
As a tester, you need to handle dropdowns in all scenarios. And for that, going without Select class is critical.
Here are a couple more reasons why:
✔️ Allows you to handle any dropdown type—native, custom, single select, multi select
✔️ Gives greater control for complex selections
✔️ Improves reliability for flaky dropdowns
Now that we know why this skill is vital —let’s look at how to actually implement it in Selenium test automation scripts.
Methods for Dropdown Handling without Select Class
Over the years, I’ve compiled a toolbox of several techniques to handle dropdowns sans Select class.
I categorize them into 5 main methods—each with its own approach:
- Find elements and iterate over options
- Use custom XPath
- Execute JavaScript
- Send keys
- Mouse hover actions
Let’s explore each of these methods in detail:
Method 1 : Find Elements and Iterate
This method involves first fetching all the dropdown options as elements, and then iterating over them to identify and click the desired option.
How it works:
- Click the dropdown element to open all options
- Fetch elements for each dropdown option into a list
- Iterate over the list until you find the desired option
- Click() on the matching option element
Example code:
//click dropdown to open
driver.findElement(By.id("color-dropdown")).click();
//all options elements
List<WebElement> options = driver.findElements(By.cssSelector("ul#colors > li"));
//iterate options
for(WebElement option : options) {
if(option.getText().equals("Red")) {
option.click();
break;
}
}
This approach works universally across any dropdown type be it select, div, ul or anything.
Plus you have full control via iterating in Java instead of built-in Select behavior.
On the flip side, constantly finding elements and iterating can get slow for large dropdowns. Attention must be paid to timeout configuration.
Method 2: Custom XPath
Instead of fetching all elements, we can directly construct an XPath matching the desired option.
Benefits include:
- No iteration needed
- Very fast execution
- Automated sync behavior
Example:
//click dropdown
driver.findElement(By.id("dropdown")).click()
//xpath for desired option
String myOptionXPath = "//div[@class=‘dropdown‘]/ul/li[text()=‘Red‘]";
//find and click option
driver.findElement(By.xpath(myOptionXPath)).click();
The downside, of course, is that it takes knowledge of XPath syntax. If you’re new that can be daunting.
Plus generating these xpaths programmatically requires some effort.
Still, I’d say it becomes easy with a bit of practice and clinics most test automation use cases.
Method 3: Use JavaScript to Click Option
You might have faced issues like—dropdown flickering repeatedly, options not visible despite clicking dropdown etc.
To eliminate these, I leverage JavaScript to reliably click the desired option element.
This avoids browser nuances and forces the click event through JavaScript. Some example code:
//dropdown selector
var dropdown = "#color-dropdown"
// desired option
var redOption = "Red";
// create click function
var jsClick = `
var dropdown = document.querySelector("${dropdown}");
var desiredOption = dropdown.querySelector("li:contains(‘${redOption}‘)");
desiredOption.click();
`
// execute click function
driver.executeScript(jsClick);
Now you don’t need to be a JavaScript expert to make this work. In 10+ years of test automation experience, I’ve found this simple pattern very effective.
Just form the right query selectors and it will handle clicking reliably.
The con here can again be around dynamically generating selectors. Plus you need basic JavaScript familiarity.
But it’s quite beginner friendly so don’t worry!
Method 4: Send Keys with Option Text
Some dropdown libraries allow directly sending the option string or text to select it.
For example:
//open dropdown
driver.findElement(By.id("dropdown")).click();
//option value
String color = "Red";
//send keys to input directly
driver.findElement(By.id("dropdown")).sendKeys(color);
This relies on the capability of dropdown components to directly accept input for option matching.
Pros:
✅ Fast, minimal code
✅ No DOM traversal needed
Cons:
❌ Not universally supported behavior
❌ May not work on all dropdowns
Still, I would recommend trying it first. And then fall back to other methods as needed.
Method 5: Mouse Hover Actions
Some dropdowns open up on mouse hover over an element. Selenium’s Actions class can handle such scenarios.
For example:
// Actions
Actions builder = new Actions(driver);
// Mouse over main element
WebElement mainElement = driver.findElement(By.id("main"));
builder.moveToElement(mainElement).perform();
// Now dropdown visible
//Select desired option
WebElement opt = driver.findElement(By.xpath("//div[@id=‘dropdown‘]/ul/li[text()=‘Red‘]"));
builder.click(opt).perform();
This allows you to handle hover activated dropdowns which is a common UI pattern.
Downsides are slower execution and only applying to hover based dropdowns.
For other types, it may not help.
Comparative Analysis
Let’s summarise the pros and cons of each approach discussed for easy comparison:
Method | Pros | Cons |
---|---|---|
Find and Iterate | Works universally Greater control via Java |
Slow for large dropdowns |
Custom XPath | Fast execution Reliable sync behavior |
Brittle xpaths XPath knowledge needed |
JavaScript Click | Very reliable Avoids browser issues |
Some JS experience needed |
Send Keys | Minimal code Very fast if works |
Limited browser support |
Mouse Hover Actions | Handles hover dropdowns | Only useful for certain dropdowns |
With this, you can decide to try out multiple approaches and see what sticks based on your dropdown behavior.
As a rule of thumb, I’d recommend trying Send Keys and Custom XPath first since they tend to work well on most modern dropdowns.
And have Find Elements and JavaScript handy to handle complex or flaky scenarios.
Now that you have a good understanding of the underlying concepts—let’s shift gears and put this into practice within a structured test automation framework.
Implementing in Test Automation Framework
While working on complex test automation initiatives, we normally use and continually evolve an automation framework to improve reusability, stability and maintainability of scripts.
As part of this, it helps greatly to create separate classes and methods dedicated to handling dropdowns without Select class.
Some best practices I’ve found useful:
🔹 Create reusable page objects for encapsulating element locators and dropdown logic
🔹 Have separate utility classes for methods like JavaScript handling
🔹 Overload methods by selection logic for easier usage in tests
Here is some sample code to give you an idea:
//DropdownHandlerUtility.java
public class DropdownHandlerUtility {
WebDriver driver;
public DropdownHandlerUtility(WebDriver driver) {
this.driver = driver;
}
public void selectByText(WebElement elem, String text) {
String myXpath = "//div[contains(@class,‘dropdown‘)]/ul/li[text()=‘"+text+"‘]";
driver.findElement(By.xpath(myXpath)).click();
}
}
// Create page object
public class CheckoutPage {
WebElement colorDropdown;
public void selectColor(String color) {
DropdownHandlerUtility handler = new DropdownHandlerUtility(driver);
//attempt send keys
colorDropdown.sendKeys(color);
//retry with custom xpath
handler.selectByText(colorDropdown, color);
}
}
// In test class
@Test
public void test() {
Checkout checkoutPage = new CheckoutPage();
checkoutPage.selectColor("Red"); // implementation hidden
}
This allows us to abstract technical implementation details into reusable classes. And overall simplify test code.
Some other tips:
- Thorough exception handling
- Extensive logging for diagnostics
- Custom configs where possible
- Handle synchronization, waits, polling etc.
That concludes my top recommendations for test automation framework design and dropdown handling!
Now let’s briefly discuss how you can further scale and augment this by leveraging online cloud infrastructure.
Powerful Test Automation with BrowserStack
While the above techniques help overcoming Selenium’s native limitations around dropdowns, testing cross-browser and cross-device brings its own challenges.
As browser/device fragmentation continues exponentially, testing manually on every permutation is impossible.
This is where BrowserStack comes into the picture.
BrowserStack essentially provides a cloud-based Selenium Grid comprised of 3000+ real mobile devices, browsers and operating systems. Enabling automated testing across this vast matrix of test environments.
By seamlessly integrating with your test framework, scripts and CI/CD pipelines, BrowserStack complements your skill of handling quirky dropdowns in Selenium.
Some unique advantages:
Access to Widest Test Coverage (4000+ Browser/OS/Device combinations)
⭐ Eliminate gaps in test coverage
Live Testing and Interactive Debugging
⭐ Visually inspect and debug across platforms
Network Simulation
⭐ 3G, 4G etc networks for reliability testing
Geographic Distribution
⭐ Test across global datacenters to simulate regional users
Parallel Testing
⭐ Drastically cuts test cycles for CI/CD integration
And quite affordably compared to the cost of procuring and maintaining thousands of devices and browsers in-house!
Here is a pictorial glimpse:
I hope you’re now convinced to try BrowserStack as well 🙂
Sign up for a free trial and you can enable mobile + web testing in literally minutes!
Let’s Recap
Phew, this turned out to be quite an epic guide!
We started with understanding why it is important to handle dropdowns without Select class in test automation.
Moved on to explore the various techniques to do so:
- Find elements and iterate options
- Construct custom XPaths
- Use JavaScript injections
- Send keys directly
- Handle hover based dropdowns
We compared the pros and cons of each approach.
Finally, we looked at how to incorporate these techniques into a structured test automation framework using page objects and utility classes.
And I shared some recommendations for efficiently integrating with BrowserStack to achieve wide test coverage.
I’m confident these best practices around dropdown handling will help you become an ace in Selenium test automation!
Whether a beginner or a seasoned expert, do share your feedback and questions. I’ll be thrilled to help you on your automation journey.
Happy testing my friend!