March 24, 2012

javascript in html head, innerhtml not working?

Question by Sam Adams

 <html>
 <head>
 <script type="text/javascript">
 document.getElementById("eee").innerHTML = "7777";
 </script>


 </head>
 <body>
 <p id="eee">aa</p>

 </body>
 </html>

why does the innerHTML not work in the head, but it does work in the body? Excuse the beginners question but last time i used javascript a year ago this was not a problem at all.

Answer by maerics

You need to wait for the HTML document to be loaded before it can be manipulated.

<script type="text/javascript">
  window.onload = function() {
    document.getElementById("eee").innerHTML = "7777";
  };
</script>

Keep in mind that scripts are evaluated in the order they are listed in an HTML document, so your script gets run while the browser is processing the “head” section. Since the browser hasn’t yet parsed the “body” section it doesn’t know about any element with id “eee”.

However, by assigning a function to the “window.onload” event, you can delay the execution of your inner HTML assignment until the window has completely loaded all of the resources and safely manipulate the document.

Note that if your script was in the body section, after the element with id “eee” was listed, then the script would work without the need to wait for the window “load” event.

Answer by Starx

Its because you script cannot find the element. The scripts in the head load first, when the DOM has been loaded properly or still is loading.

<p id="eee">aa</p>
<!-- Use the script after the element, so that the script can find it -->
<script type="text/javascript">
 document.getElementById("eee").innerHTML = "7777";
</script>

Other methods may be executing the script on the onload events of the window

window.onload = function() {
    document.getElementById("eee").innerHTML = "7777";
};

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!