title: What's the difference between putting script in head and body?
body: <p>I was getting a problem .</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;head&gt;
    &lt;meta http-equiv="content-type" content="text/html; charset=utf-8" /&gt;
    &lt;script type="text/javascript"&gt;
    alert(document.getElementsByTagName("li").length); 
    &lt;/script&gt;
    &lt;title&gt;purchase list&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;What to buy&lt;/h1&gt;
    &lt;ul id="purchases"&gt;
      &lt;li&gt; beans&lt;/li&gt;
      &lt;li&gt;Cheese&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>When I put scripts in head, the result shows 0</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
                        "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt; 
  &lt;head&gt;
    &lt;meta http-equiv="content-type" content="text/html; charset=utf-8" /&gt;
    &lt;title&gt;Shopping list&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;What to buy&lt;/h1&gt;
  
    &lt;ul id="purchases"&gt;
      &lt;li&gt;Cheese&lt;/li&gt; 
      &lt;li&gt;Milk&lt;/li&gt;
      &lt;script type="text/javascript"&gt;
      alert(document.getElementsByTagName("li").length);
      &lt;/script&gt;
    &lt;/ul&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>When I tried to put scripts in body, the result shows 2. why there is such a difference?
  what is the main difference?</p>