Forms, Dropdowns, and Alerts
Selenium's Select class for real dropdown semantics, and switching context to handle a native browser alert — both requiring more deliberate handling than a plain click.
What you'll learn
- Use the Select class correctly for a <select> dropdown, choosing the right selection method
- Handle a native browser alert/confirm/prompt by switching WebDriver's target
- Explain why clicking a dropdown's visible option directly is a fragile alternative to Select
Prerequisites
Explanation
A standard HTML <select> dropdown has real, specific semantics Selenium models with a dedicated Select class, not plain WebElement clicks: new Select(driver.findElement(By.id("country"))).selectByVisibleText("Canada") selects by the option's displayed text; .selectByValue("CA") selects by the option's underlying value attribute (often more stable than display text, which might change for localization or copy reasons while the underlying value stays the same); .selectByIndex(2) selects positionally. Select also correctly handles multi-select dropdowns (isMultiple(), and selectByVisibleText called multiple times adds to the selection rather than replacing it) — behavior that clicking individual <option> elements directly does not correctly replicate, especially for multi-select.
Interacting with a dropdown by finding and clicking its visible <option> elements directly (bypassing Select) is a fragile alternative for a specific, concrete reason: some browsers render a native <select>'s open dropdown list using OS-level UI that isn't part of the page's regular DOM rendering in the way Selenium can reliably interact with — Select works around this entirely by manipulating the underlying <select> element's state directly, through the same DOM API mechanism regardless of how any particular browser happens to render the open dropdown visually.
A native browser alert, confirm, or prompt dialog is not part of the page's DOM at all — it's rendered by the browser itself, outside the page — so driver.findElement(...) can never find or interact with it; attempting to interact with the page while a native dialog is open typically throws UnhandledAlertException. Handling one requires switching WebDriver's target: Alert alert = driver.switchTo().alert(); gives you a handle specifically to the open dialog, with alert.accept() (OK), alert.dismiss() (Cancel), alert.getText() (read its message), and — for a prompt() specifically — alert.sendKeys(text) before accept() to fill in the response. After handling it, WebDriver's context automatically returns to the main page — there's no explicit "switch back" call needed for alerts specifically, unlike frames (covered later in this course), which do require an explicit switch back.
Example
Modeling Select's value-vs-text distinction and the alert switchTo() pattern as data, mirroring the real API's structure.
class FakeSelectElement {
constructor(options) { this.options = options; this.selected = null; } // options: [{value, text}]
selectByValue(value) {
const match = this.options.find((o) => o.value === value);
if (!match) throw new Error("no option with value " + value);
this.selected = match;
}
selectByVisibleText(text) {
const match = this.options.find((o) => o.text === text);
if (!match) throw new Error("no option with text " + text);
this.selected = match;
}
}
const countryDropdown = new FakeSelectElement([{ value: "CA", text: "Canada" }, { value: "US", text: "United States" }]);
countryDropdown.selectByValue("CA");
console.log(countryDropdown.selected); // { value: "CA", text: "Canada" } -- selected by the STABLE value, not display text
function handleAlert(alertPresent, action) {
if (!alertPresent) throw new Error("no alert is currently open -- switchTo().alert() would fail here");
return action === "accept" ? "OK clicked" : "Cancel clicked";
}
console.log(handleAlert(true, "accept")); // "OK clicked"Try it yourself
Call handleAlert with alertPresent set to false and observe it correctly throw instead of silently doing nothing.
Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.
Guided exercise
Guided exercise
Model Select: write class SelectModel with a constructor(options) (options: [{value,text}]) storing options and selected=null, and a method selectByValue(value) that finds the matching option and sets this.selected to it, or throws if no match exists.
Checks: selects the correct option by value · throws when selecting a non-existent value
Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.
Stuck? Get a hint.
Independent exercise
Independent exercise
Write selectMultiple(selectModel, values) that calls selectModel.selectByValue for EACH value in values, and ALSO tracks every selection in a NEW array selectModel.allSelected (initialize it if it doesn't exist) -- modeling how a real multi-select adds to the selection rather than replacing it on each call.
Checks: accumulates multiple selections correctly, matching real multi-select behavior · handles an empty values list
Code editor. Press Escape then Tab to leave the editor if keyboard focus becomes trapped. Press Control+Shift+M inside the editor to toggle Tab-key focus trapping.
Stuck? Get a hint.
Common mistakes
- Finding and clicking a dropdown's <option> elements directly instead of using the Select class -- some browsers render an open native dropdown using OS-level UI Selenium can't reliably interact with this way; Select works around this by manipulating the underlying element's state directly.
- Selecting by visible text when the underlying value is what's actually stable -- display text can change for localization or copy reasons while the value attribute stays the same; selectByValue is often the more resilient choice.
- Trying to findElement() while a native alert is open -- this throws UnhandledAlertException; the alert must be switched to and handled (accepted or dismissed) before any other page interaction can proceed.
Knowledge check
Takeaway
Use the Select class for real <select> dropdown semantics rather than clicking options directly, prefer selectByValue when the underlying value is more stable than display text, and handle native alerts by explicitly switching WebDriver's target to them before any other page interaction can proceed.
Summary
Select's selectByValue/selectByVisibleText/selectByIndex correctly handle single and multi-select dropdowns through the underlying element's state, avoiding browser-specific rendering issues with direct option-clicking. Native alerts aren't part of the page DOM; driver.switchTo().alert() is required to accept(), dismiss(), getText(), or sendKeys() to a prompt before other page interaction can resume.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.