john
john

Reputation: 23

script tag doesn't work in head tag

script tag doesnt execute if i put it in head tag but works fine if i put it in body tag ..can anybody tell me the reason behind this?? here's my code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>

<body>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Date();
</script>


</body>

</html>

Upvotes: 2

Views: 2630

Answers (2)

user5250554
user5250554

Reputation:

The <head> is for including other files and libraries and such (you can also include them in the body). But if you want to actually write JS code to manipulate the body, you have to place it in the body.

Upvotes: 0

Romain
Romain

Reputation: 817

That's because HTML is parsed from top to bottom. That means that when you try to get the element demo it is not yet created.

To make it work in the head tag you should add a listener that will fire when the page is fully loaded.

document.addEventListener("DOMContentLoaded", function() {
  // Here the DOM elements are loaded, and you can get them with .getElementById.
  document.getElementById("demo").innerHTML = Date();
});

Upvotes: 6

Related Questions