Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript code place in the header

I am not clear why its not working the javascript code when I add it to the header section as follows.

We can place a javascript code within the body as follows

<html> 

 <head>
    <title> Simple Test </title>    
 </head>
 <body>
        <div id="mydiv"> This is the div content </div>

        <script type="text/javascript" >
           document.getElementById("mydiv").innerHTML=Date();         
        </script>   

 </body>
</html>

But when I place the same JavaScript code in the header section it doesn't work.

<html>
  <head>
   <title> Simple Test </title>

   <script type="text/javascript" >
      document.getElementById("mydiv").innerHTML=Date();         
   </script>    

  </head>

Can Someone please explain the issue. I know I can Write a JavaScript function in header and call it in an event. But can't we Use in this way. If Can't why.

like image 407
JibW Avatar asked Jun 30 '26 03:06

JibW


2 Answers

<html>
  <head>
   <title> Simple Test </title>

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

I think above code will help you to solve your problem. You can try this one.

like image 168
tareq_moinul Avatar answered Jul 01 '26 18:07

tareq_moinul


because when the page is loaded, by the time the browser gets to that <script> element, the #mydiv element has not yet been created.

either use an "onload" event, or put your scripts at the bottom of the page.

like image 29
Kae Verens Avatar answered Jul 01 '26 17:07

Kae Verens