Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

trying to get the date and time onto an html page with javascript page. code isn't working in browser.

code on javascript page:

script type="text/javascript"> getCurrentDateTime(); function getCurrentDateTime() { document.getElementById("timeDiv").innerHTML = new Date(); }

code on html page:

<div id="timeDiv"></div>

2 Answers

Hope this helps you see where you might have been going wrong. Feel free to ask questions about the solution.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="timeDiv"></div>
    <script>
        function getCurrentDateTime() {
            document.getElementById('timeDiv').innerHTML = new Date();
        }

        getCurrentDateTime();
    </script>
</body>
</html>

I tried this code on a javascript page and an html page and it doesn't work. I know that the javascript page is linked correctly because the code from the .js file is showing in the browser. I even tried copying and pasting this code and it still doesn't work. On the html page I even put the script code right under the <body> tag and it still isn't working. what am I doing wrong. Thank you

Ensure you add the javascript file after you have already created the div identified by the 'timeDiv' Id on the page ie

<div id="timeDiv"><div>
.......
......
<script src="*.js"></script>