What's the difference between putting script in head and body?

I was getting a problem .

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <script type="text/javascript">
  alert(document.getElementsByTagName("li").length); 
  </script>
  <title>purchase list</title>
</head>
<body>
  <h1>What to buy</h1>
  <ul id="purchases">
    <li> beans</li>
    <li>Cheese</li>
  </ul>
</body>

When I put scripts in head, the result shows 0

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
                      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Shopping list</title>
</head>
<body>
  <h1>What to buy</h1>

  <ul id="purchases">
    <li>Cheese</li> 
    <li>Milk</li>
    <script type="text/javascript">
    alert(document.getElementsByTagName("li").length);
    </script>
  </ul>
</body>

When I tried to put scripts in body, the result shows 2. why there is such a difference? what is the main difference?


Solution 1:

What's the difference between putting script in head and body?

The time that it runs.

When I put scripts in head, the result shows 0 Shopping list

The elements you are trying to access don't exist when the script runs (since they appear after the script in the document).

Note that you can write a script so that a function is called later (for various values of later including "when the entire document has loaded") using event handlers.

Solution 2:

It's simple, JavaScript will go from up-down, unless you tell it to do something else. By the time it reaches the li elements, the JavaScript code has already been completed.

If you want to keep it in the head however, you could use the document.ready function and it will load only after the HTML it's loaded.