0

Here's my code:

<html>
<head>
<title>Date Test</title>
<script>
document.getElementById("date").innerHTML = Date();
</script>
</head>
<body>
<p>Today's date is <span id="date"></span></p>
</body>
</html>

When I run the HTML document, it only shows "Today's date is"... WHY?!?

Sam Clark
  • 369
  • 3
  • 6
  • 12

2 Answers2

5

The <span id="date"> doesn't exist when the script is executed. You can put it in an onload handler to fix this:

<script>
onload = function() {
    document.getElementById("date").innerHTML = Date();
};
</script>

That will run the script sometime after the entire DOM is ready. Of course, you can handle DOMContentLoaded to run the code immediately when the DOM is ready, and not after its contents have also loaded, but the other (really easy) way is to put your script before the closing </body> tag:

<html>
<head>
<title>Date Test</title>
</head>
<body>
<p>Today's date is <span id="date"></span></p>
<script>
document.getElementById("date").innerHTML = Date();
</script>
</body>
</html>
Ry-
  • 199,309
  • 51
  • 404
  • 420
3

Try placing the script right before the end of the body to ensure that the DOM has loaded:

<html>
<head>
<title>Date Test</title>
</head>
<body>
<p>Today's date is <span id="date"></span></p>
<script type="text/javascript">
document.getElementById("date").innerHTML = Date();
</script>
</body>
</html>

Example: http://jsfiddle.net/tQUUH/

Here are some resources that go a little deeper on the topic:

If you're just learning JavaScript, MDN is a great resource.

Community
  • 1
  • 1
Andrew Whitaker
  • 119,029
  • 30
  • 276
  • 297