简体   繁体   中英

javascript - Why doesn't innerHTML replacing run?

<!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?

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 .

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM