开发者

getElementsByTagName().length returns zero

I am trying to do a simple thing such as:

var elements = document.getElementsByTagName("inp开发者_如何学JAVAut");
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.

I've also seen this getElementsByTagName("div").length returns zero for any webpage however 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.

Anyone could help me out?


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

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>


This happens because of the asynchronous behaviour of JS. You're trying to display the element's value before it is being rendered. In order to avoid it, you could add the "async" attribute to your tag, as in the following example:

<script type="text/javascript" src="myTag.js" async></script>


your script should have the attribute "deter" to detect the tags

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜