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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.