1

The script runs before the document loaded, so why does console.log(b) show elements in the collection?

If console.log(b) has elements then why does console.log(b[0]) show undefined and console.log(b.length) 0?

<html> 
    <head> 
    
    <script>
        function test(){
            var b = document.getElementsByName('a');
            console.log(b);
            console.log(b[0]);
            console.log(b.length);
        }
        test();
    </script>
    </head>
    
    <body>
    <form id="a" name="a"></form>
    </body>
</html>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
bizet
  • 53
  • 1
  • 7
  • because you have no any elements in your form ? – Roni Tovi Nov 14 '14 at 15:05
  • 4
    The collection returned is a "live list". It automatically updates as items are added to and removed from the DOM. Therefore the console view of the collection shows its current state when you view it, whereas the `b[0]` view gets the state of when you made the `console.log()` call. –  Nov 14 '14 at 15:06
  • You could wait for the DOM to be ready, this might help: http://api.jquery.com/ready/ – mparkuk Nov 14 '14 at 15:10
  • 1
    You are seeing the effect of: [Is Chrome's JavaScript console lazy about evaluating arrays?](http://stackoverflow.com/q/4057440/218196) ... maybe that's the actual duplicate. – Felix Kling Nov 14 '14 at 15:11
  • If you use Chrome console, read the `(i)` icon hint: `Object state below is captured upon first expansion` –  Nov 14 '14 at 15:22

1 Answers1

1

getElementsByName returns a NodeList. It's an object containing the list of matching nodes, so b is not null.

However, you're running the script before the DOM is ready, so the list is of length 0 with no first object. You need to delay the script execution until after the DOM's been parsed, at which point the form will exist.

mjk
  • 2,443
  • 4
  • 33
  • 33