My goal is to make my JavaScript code function properly when I insert it into either the head
or body
elements of an HTML document.
Let's look at some examples:
First, I insert the script into the body
as shown in this example (works correctly):
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
Next, when I move the script
to the end of the body
(still works correctly):
<html>
<body>
<p id="p2">Hello World!</p>
<p>The paragraph above was changed by a script.</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</body>
</html>
However, if I place the script in the head
, it fails to work:
<html>
<head>
<script>
document.getElementById("p2").style.color = "blue";
</script>
</head>
<body>
<p id="p2">Hello World!</p>
<p>The paragraph above was changed by a script.</p>
</body>
</html>