为什么属性.options不适用于由DOM方法querySelectorAll选择的select,而只适用于getElementById?我需要使用querySelector。
var sel = document.querySelectorAll('.current .od select #mySelect');
sel.options
返回:未定义
var sel = document.getElementById('mySelect');
sel.options
return:选项列表
querySelectorAll
返回一个NodeList
,而不是单个元素,并且NodeList
实例没有options
属性。
要获得单个元素,请使用querySelector
(无"全部"):
var sel = document.querySelector('.current .od select #mySelect');
sel.options
当然,如果在某个时候你想处理一个列表,可以索引到它:
var sel = document.querySelectorAll('select');
sel[0].options
// ^^^
旁注:如果#mySelect
元素位于文档的不同部分,则除非您想返回null
,否则根本没有理由使用该子代选择器的所有这些部分。只有document.querySelector('#mySelect')
和document.getElementById('mySelect')
会有相同的结果(但速度会快很多,这通常并不重要)。