Javascript getElementsByTagName().length 返回零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5844732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:10:10  来源:igfitidea点击:

getElementsByTagName().length returns zero

javascriptgetelementsbytagname

提问by mobius

I am trying to do a simple thing such as:

我正在尝试做一件简单的事情,例如:

var elements = document.getElementsByTagName("input");
console.log(elements);
console.log(elements.length);

The console.log(elements) shows the NodeList containing 28 input elements, but the elements.length is always 0.

console.log(elements) 显示包含 28 个输入元素的 NodeList,但 elements.length 始终为 0。

I've also seen this getElementsByTagName("div").length returns zero for any webpagehowever I didn't understand what exactly is the reason for it happening and how to fix it. I've also noticed that this happens on both Firefox, IE, Chrome.

我还看到这个getElementsByTagName("div").length 对于任何网页都返回零,但是我不明白它发生的确切原因是什么以及如何修复它。我还注意到这在 Firefox、IE、Chrome 上都会发生。

Anyone could help me out?

任何人都可以帮助我吗?

采纳答案by c-smile

NodeListis a live collection and non-deferred scripts execute immediately (see script defer).

NodeList是一个实时集合,非延迟脚本会立即执行(请参阅脚本延迟)。

Try this and you will get an idea of what happens:

试试这个,你会知道会发生什么:

<html>
<head>
  <title></title>
  <style></style>
  <script type="text/javascript">
    var elements = document.getElementsByTagName("div");
    alert(elements.length); 
  </script>
</head>
<body>
  <div>1</div>
  <script type="text/javascript">
    //var elements = document.getElementsByTagName("div");
    alert(elements.length); 
  </script>
</body>
</html>