0

As you can see below,it will run without 'window.onload' and var x is '[<div class="myInput"></div>]',but not '[]'.

<html>
<head>
    <script type="text/javascript">
        var x=document.getElementsByClassName("myInput");
    </script>
</head>
<body>
    <div class="myInput"></div>
</body>
</html>

how and when it put the element into the array?

jinsihou
  • 161
  • 1
  • 9

2 Answers2

1

x is a live HTMLCollection of found elements, meaning it is automatically updated when the underlying document is changed (in this case, as it loads).

So the value of x initially is different than it is when the document is loaded:

<html>
<head>
    <script type="text/javascript">
        var x=document.getElementsByClassName("myInput");
        document.write('Initial: ', x, '<br>');
        document.write('Initial Length: ', x.length, '<br>');
    </script>
</head>
<body>
    <div class="myInput"></div>
  
    <script type="text/javascript">
        document.write('Final: ', x, '<br>');
        document.write('Final Length: ', x.length, '<br>');
    </script>
</body>
</html>
rnevius
  • 26,578
  • 10
  • 58
  • 86
-2

The HTML document is read by the browser from top to bottom. While in the head, if you attempt to do x = document.getElementsByClassName("classname") there are no elements present as the browser has still not read anything after the script tag's 1st line.

Later on the browser would read the <body> tag, create elements and if you call it at that point with onload you would get the list.

Dellirium
  • 1,362
  • 16
  • 30
  • downvoted for saying correct things with no comment as on why, interesting. – Dellirium Apr 10 '16 at 12:22
  • You can try my code ,and x is `[
    ]` in chrome.
    – jinsihou Apr 10 '16 at 12:23
  • Oh wait I misunderstood the question, so the question is why it CAN and not why it CAN'T? It does seem weird that it can though, but I do not see what the issue there is. – Dellirium Apr 10 '16 at 12:25
  • @Dellirium Downvoted because your answer is wrong and the accepted (correct) one was already posted. – pishpish Apr 11 '16 at 10:19
  • At the time of me witting this there was no answer. The answer is wrong as I did mis-interpret the question, as noted. The guy asked why it CAN be accessed, whilst I figgured that the question was why it cannot. – Dellirium Apr 11 '16 at 10:21