select Element Reads Selected Options
Read a select through value, selectedIndex, options, and selectedOptions; programmatic value assignment fires change just like user selection.
Code
const select = document.querySelector<HTMLSelectElement>("#env");
if (!select) throw new Error("select markup missing");
function describeSelection(): string {
// value 总是字符串;selectedIndex 指向 options 里的位置
const option = select.options[select.selectedIndex];
return `${select.value} @ index ${select.selectedIndex} (${option?.text ?? "none"})`;
}
console.log(describeSelection());
select.addEventListener("change", () => {
console.log(describeSelection());
// selectedOptions 处理 multiple 场景:单选时长度恒为 1
const chosen = [...select.selectedOptions].map((option) => option.value);
console.log(`selected: ${chosen.join(",")}`);
});
// 程序化切换与手动选择走同一条 change 路径
select.value = "staging";
select.dispatchEvent(new Event("change"));
What the snippet does
The load-bearing code sits in the function describeSelection — everything else is wiring.
The failure path is explicit — Error is raised when the guard condition holds.
Points of care
- Built-in APIs only, so there is no supply chain to vet.
document.querySelector,HTMLSelectElementanddispatchEventare browser-only surfaces — run this in a page, not a bare Node process.- The guard
!selectshort-circuits the flow with an earlythrowwhen its condition holds.
Using it
function describeSelection() composes its answer from three reads — select.value, select.selectedIndex, and select.options[select.selectedIndex]?.text.
Look for the selected: $ prefixes when the file runs; they tie each line to its step.
Key statements
return `${select.value} @ index ${select.selectedIndex} (${option?.text ?? "none"})`;
select.addEventListener("change", () => {
console.log(describeSelection());
// selectedOptions 处理 multiple 场景:单选时长度恒为 1
const chosen = [...select.selectedOptions].map((option) => option.value);
console.log(`selected: ${chosen.join(",")}`);
});
if (!select) throw new Error("select markup missing");
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Is there a failure path for bad input?
- The code throws `Error` — the guard `!select` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Does select Element Reads Selected Options run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.