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

Hello, everyone. I was got a problem and need some help.

<!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" />
<script type="text/javascript">
alert(document.getElementsByTagName("li").length);
</script>
<title>Shopping list</title>
</head>
<body>
<h1>What to buy</h1>
<p title="a gentle reminder">Don’t forget to buy this stuff.</p>
<ul id="purchases">
<li>A tin of beans</li>
<li>Cheese</li>
<li>Milk</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>
<p title="a gentle reminder">Don’t forget to buy this stuff.</p>
<ul id="purchases">
<li>A tin of beans</li>
<li>Cheese</li>
<li>Milk</li>
<script type="text/javascript">
alert(document.getElementsByTagName("li").length);
</script>
</ul>
</body>

When I put scripts in body, the result shows 3. why there is such a difference?

Without knowing a lot about javascript, I would say it is because in the first example the li tags don’t “exist” as they haven’t yet been “drawn.”

try putting the code after the first 2 li tags but before the 3rd and I bet it gives you 2.

Script code is executed when the browser encounters it while loading the page.

If you put the script in the head, you are referencing an element that doesn’t exist – because the browser hasn’t got that far yet. If you must have the script in the head, you need to use an event listener for, e.g., document.onload.

By putting the script at the end of the body, you can be certain that all elements exist, because the browser has parsed the markup and created the DOM tree by then.

Thank you AutisticCuckoo! a very clear illustration.:slight_smile: Thank you corbyboy too :slight_smile: