getElementsByTagName().length returns zero

前端 未结 3 424
臣服心动
臣服心动 2021-01-04 20:17

I am trying to do a simple thing such as:

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


        
相关标签:
3条回答
  • 2021-01-04 20:31

    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>
    
    0 讨论(0)
  • 2021-01-04 20:36

    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>
    
    0 讨论(0)
  • 2021-01-04 20:47

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

    0 讨论(0)
提交回复
热议问题