+ 2

Changing html with javascript

I have the following html code: <!DOCTYPE html> <html> <head> <title>Test Website</title> <script src = "testsite.js"></script> </head> <body> <div>Current time:</div> <div id = "currentTime">00:00:00</div> </body> </html> and the following javascript code: var item = document.getElementById("currentTime"); var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); item.innerHTML = hours + ":" + minutes + ":" + seconds; but for some reason it's not working. I've already tested that the script is correctly added to the website (by replacing it with alert("test")), and the problem seems to be either the selecting or the changing of the element.

26th Nov 2017, 8:08 PM
Fabian de Korver
Fabian de Korver - avatar
10 Respuestas
+ 1
The main html elements on which JS code operates are loaded in the <body>. Executing JS code in <head> even before the target html elements are loaded may result in unexpected behavior in the page. Hence, it is advised that you put your JS towards the end of <body>, i.e. just before </body>.
27th Nov 2017, 5:13 AM
Anil
Anil - avatar
+ 2
what's with the */ at the end of getSeconds() ? have you block-commented out your code?
26th Nov 2017, 3:05 PM
Anil
Anil - avatar
+ 1
have you tried wrapping your code inside an onload function? or a jquery ready???
26th Nov 2017, 8:27 PM
Dmitrii
Dmitrii - avatar
0
I had but I'd already removed the first part (/*). Removed it but it still doesn't work.
26th Nov 2017, 6:22 PM
Fabian de Korver
Fabian de Korver - avatar
0
Could u post a link to ur entire code html & JavaScript?
26th Nov 2017, 6:43 PM
Anil
Anil - avatar
0
Updated it with the full code
26th Nov 2017, 8:09 PM
Fabian de Korver
Fabian de Korver - avatar
0
<script src = "testsite.js"></script> needs to point the correct path of the script file. you might have the script file in Project_path/js, by mistake. more here https://www.digitalocean.com/community/tutorials/how-to-add-javascript-to-html
26th Nov 2017, 8:18 PM
Dmitrii
Dmitrii - avatar
0
The src points to the correct script, I tested it by commenting everything out and replacing it with alert("test") which gave me a prompt when loading the webpage. I've not tried an onload function or jquery, I'm not sure what those are actually.
27th Nov 2017, 1:19 AM
Fabian de Korver
Fabian de Korver - avatar
0
Because your script is loaded within the head tag, it executes before the body is loaded. Put a window.onload = function() { ... } around the JS code indicated by the ...
27th Nov 2017, 4:46 AM
John Wells
John Wells - avatar
0
Thanks! That fixed it.
27th Nov 2017, 10:45 AM
Fabian de Korver
Fabian de Korver - avatar