title: Why does document.getElementsByName have a length of 0 despite having elements?
body: <p>The script runs before the <code>document</code> loaded, so why does <code>console.log(b)</code> show elements in the collection?</p>
  
  <p>If <code>console.log(b)</code> has elements then why does <code>console.log(b[0])</code> show <code>undefined</code> and <code>console.log(b.length)</code> <code>0</code>?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; 
      &lt;head&gt; 
      
      &lt;script&gt;
          function test(){
              var b = document.getElementsByName('a');
              console.log(b);
              console.log(b[0]);
              console.log(b.length);
          }
          test();
      &lt;/script&gt;
      &lt;/head&gt;
      
      &lt;body&gt;
      &lt;form id="a" name="a"&gt;&lt;/form&gt;
      &lt;/body&gt;
  &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>