[英]How do i get the first option in a select in JavaScript?
I want to get the first option from a select.我想从 select 中获得第一个选项。 Does this work?
这行得通吗?
dropDown = document.querySelector(".select")
if (dropDown[0].innerHtml === '0'){
console.log('yes')
}
dropDown
is my select. dropDown
是我的 select。 Inside there is option value=o>o</option
.里面有
option value=o>o</option
。 This logs "yes" but it gives an error:这记录“是”,但它给出了一个错误:
Uncaught TypeError: dropDown[i] is undefined
未捕获的类型错误:dropDown[i] 未定义
My rookie mind went this way:我的菜鸟想法是这样的:
const dropDown = document.querySelectorAll(".select > option")
if (dropDown[0].innerHtml === '0'){
console.log('yes')
}
or if you need to have different types of actions based on the options:或者如果您需要根据选项执行不同类型的操作:
options.foreach(option => {
switch(option.innerHTML) {
case "value":
// code block
break;
case "value2":
// code block
break;
default:
// code block
}
Welcome to Stack Overflow.欢迎来到堆栈溢出。
dropDown = document.querySelector(".select") // this will always return only one element.
if (dropDown.innerHtml === '0'){ // So no need to add `dropdown.innerHTML[0]`
console.log("yes");
}
Let me know if you need further support.如果您需要进一步的支持,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.