JulioBordeaux
JulioBordeaux

Reputation: 504

Why javascript doesnt get element by id when that element is below script tag?

I'm learning javascript and studying this example:

<html>
 <body>

  <p id="p1">Hello World!</p>

  <script>
   document.getElementById("p1").innerHTML="New text!";
  </script>

 </body>
</html> 

My question is why doesn't the script work properly when the line with <p id="p1">Hello World!</p> is below the script, and what happens during its execution? Thank you.

Upvotes: 4

Views: 1571

Answers (3)

Ben Smith
Ben Smith

Reputation: 20230

Javascript is an interpreted language. 'interpreted' means that it:

"executes instructions directly, without previously compiling a program into machine-language instructions"

Hence because the javascript interpreter executes instructions on the page line by line (starting from the top of the page), the order in which code is defined is crucial. So in your example the paragraph element has to be defined before your call to getElementById.

Upvotes: 2

David Thomas
David Thomas

Reputation: 253396

Because the JavaScript is run when the browser encounters it, when compiling/rendering the page; not once it's finished rendering the page. So, if the element appears after the script it doesn't (yet) exist at the point at which the JavaScript is run.

You could, though, create a function and have that function run once an element has loaded, for example:

<script>
    function bodyLoaded(){
        document.getElementById('p1').innerHTML = 'New text!';
    }
</script>
<body onload="bodyLoaded()">
    <!-- HTML here... -->
    <p id="p1"></p>
</body>

Upvotes: 3

StackSlave
StackSlave

Reputation: 10627

Elements must be defined in order for JavaScript to recognize them. If you chose to put your JavaScript inside the <head> tag, then you can do this with the window.onload event. This can be done several ways.

//Obtrusive JavaScript
<html>
  <head>
    <script>
      function loadMe(){
        var doc = document;
        function E(e){
          return doc.getElementById(e);
        }
        E('p1').innerHTML = 'New text!';
      }
    </script>
  </head>
<body onload='loadMe'>
  <p id='p1'>Hello World!</p>
</body>
</html>
/* Unobtrusive JavaScript ---> the way you should learn it in my opinion
   Notice there's no onload attribute in the body tag. Also, I use onload
   instead of window.onload, because window is implicit, just as document
   is a property of window as well.
*/
<html>
  <head>
    <script>
      onload = function(){
        var doc = document;
        function E(e){
          return doc.getElementById(e);
        }
        E('p1').innerHTML = 'New text!';
      }
    </script>
  </head>
<body>
  <p id='p1'>Hello World!</p>
</body>
</html>

Of course, you should use external JavaScript whenever possible.

Upvotes: 1

Related Questions