0
<!DOCTYPE HTML>
<html>
<head>
<script>
document.write("TEST1")
document.getElementById("demo").innerHTML="TEST2"
document.write("TEST3")
</script>
</head>

<body>
<p id="demo">TO_BE_REPLACED</p>
</body>
</html>

Here is the output: TEST1

TO_BE_REPLACED

It seems the javascript executing stopped at document.getElementById("demo").innerHTML="TEST2". Why doesn't it execute?

CDT
  • 8,269
  • 15
  • 55
  • 89
  • 3
    See this : http://stackoverflow.com/questions/5704924/executing-javascript-in-the-head-getelementbyid-returns-null , http://stackoverflow.com/questions/8864776/getelementbyid-and-null-why , http://stackoverflow.com/questions/5371047/getelementbyid-returns-null-even-though-the-element-exists or http://stackoverflow.com/questions/10839271/null-return-by-getelementbyid-method-in-javascript – HoLyVieR Feb 19 '13 at 02:45

2 Answers2

3

When the script is being run, <p id="demo"> does not exist yet. Therefore, document.getElementById('demo') is returning null, which then triggers an error when you try to assign null.innerHTML = "TEST2"

This error stops all execution, so you never get to see the final TEST3.

Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
1

You need to enclose your script in a function that will be called when the window loads (using "window.onload" event).

<!DOCTYPE HTML>
<html>
<head>
<script>
    function replaceDemoText()
    {
        document.getElementById("demo").innerHTML="TEST2";
    }
    window.onload = replaceDemoText;
</script>
</head>

<body>
<p id="demo">TO_BE_REPLACED</p>
</body>
</html>
peter.aryanto
  • 472
  • 3
  • 6