I’ m new to javascript and I was wondering why in this script the document.write works well while innerHTML doesn’t(I’ve given a div id timer in the body). Is it that innerHTML needs Onload event in the body part of html? If so why? (I’m calling the function writehere() in the head section of html document.
<script language="javascript">
function writehere()
{
document.write("hello");
var Timer = document.getElementById("timer");
Timer.innerHTML = "hello";
}
writehere();
</script>
html code goes here…..
Most likely your issue is that the DOM isn’t ready yet by the time your code executes. For your example you can probably just move it down to the bottom of your page and it will work.
In general you would want to make sure that the DOM is fully loaded before executing your javascript that needs to interact with the DOM, if you are using jQuery you can call your code in the document ready function to ensure the DOM is loaded, for example
Have a look at this SO question for vanilla javascript equivalents
What is the non-jQuery equivalent of '$(document).ready()'?