当我从页面中选择一些元素时不小心使用了 querySelector
而不是 querySelectorAll
时,我发现了一些有趣的事情。我通常在查询后直接将静态节点列表转换为数组。但是由于 querySelector
只返回它找到的第一个匹配节点,而不是 NodeList
,我的脚本试图将 select
节点转换为数组。它没有返回空数组,而是返回了选择元素的子元素。
为什么将 select
元素转换为数组会返回子节点?这不适用于其他元素,例如 div
:
var selectParent = document.querySelector('.selectParent');
var selectArray = Array.from(selectParent);
console.log(selectArray);
var divParent = document.querySelector('.divParent');
var divArray = Array.from(divParent);
console.log(divArray);
<select class="selectParent">
<option>Option 1</option>
<option>Option 2</option>
</select>
<div class="divParent">
<div>Div 1</div>
<div>Div 2</div>
</div>
最佳答案
这主要是历史兼容性问题。 HTMLSelectElement
具有类数组所需的两个关键要素:
- 一个
长度
- 索引式访问
...而这两件事与它的选项有关:length
是框中 option
元素的数量,[0]
、[1]
等访问那些 option
元素。
上面链接的关键引述是:
The
options
collection is also mirrored on theHTMLSelectElement
object. The supported property indices at any instant are the indices supported by the object returned by theoptions
attribute at that instant.
和
The
length
IDL attribute must return the number of nodes represented by theoptions
collection...
关于javascript - 为什么将 select 元素转换为数组会返回一个子元素数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38463260/