javascript - 为什么将 select 元素转换为数组会返回一个子元素数组?

标签 javascript html arrays

当我从页面中选择一些元素时不小心使用了 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 the HTMLSelectElement object. The supported property indices at any instant are the indices supported by the object returned by the options attribute at that instant.

The length IDL attribute must return the number of nodes represented by the options collection...

关于javascript - 为什么将 select 元素转换为数组会返回一个子元素数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38463260/

相关文章:

javascript - 当模态内容是链接 href 时,bootstrap 模态检测按下了哪个按钮

Java 循环遍历 JSON 数组并编辑值

c - 如何通过提取部分数组来填充数组

javascript - 调用 ajax 调用序列的模式?

javascript - 如何使用 React Hooks 捕获最后一个输入字母

javascript - AngularJS 对 HTML5 输入日期的验证

javascript - 使用 Polymer 中元素之间的交互将对象添加到数组

php - 查找数组中的最大值

javascript - 捕获 Enter 键以导致使用 javascript 单击按钮

javascript - 为 url 上的某些 div 传递 jquery 向上滑动命令?