Lowest price ever! Learn Generative AI for 48% less!
Get my discount+ 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.
10 Answers
+ 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>.
+ 2
what's with the */ at the end of getSeconds() ?
have you block-commented out your code?
+ 1
have you tried wrapping your code inside an onload function?
or a jquery ready???
0
I had but I'd already removed the first part (/*). Removed it but it still doesn't work.
0
Could u post a link to ur entire code html & JavaScript?
0
Updated it with the full code
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
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.
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 ...
0
Thanks! That fixed it.