首页 > 解决方案 > SO Snippet 无法正确读取 childNodes

问题描述

在 Snippets 中运行以下命令将打印undefined和 5,而不是“一”和 2:

const test = () => {
  const select = document.getElementById("select");
  const item0 = select.childNodes[0];
  console.log(item0.innerText);
  console.log(select.childNodes.length);
}
<select id="select" onchange="test()">
  <option value='1'>One</option>
  <option value='2'>Two</option>
</select>

似乎第一个<option>childNodes[1]. 在网页中运行时,第一个childNodes是第一个<option>.

在普通网页中,childNodes.length<option>元素的数量。

这是沙盒环境的错误还是已知限制?

标签: code-snippets

解决方案


推荐阅读