Why is there only one sentence that can be implemented?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script>
        window.onload = function(){
        var mybox = document.getElementsByTagName("li");
        document.write("<xmp>"+mybox[0].innerHTML+"</xmp>");
        alert(mybox[0].innerHTML);
        console.log(mybox[0].innerHTML);
        }
    </script>
</head>
<body>
    <ul id="box">
        <li><img src="image/i1.png" alt=""></li>
        <li><img src="image/i2.png" alt=""></li>
        <li><img src="image/i3.png" alt=""></li>
    </ul>    
</body>
</html>

I found

        window.onload = function(){
        var mybox = document.getElementsByTagName("li");
        document.write("<xmp>"+mybox[0].innerHTML+"</xmp>");
        alert(mybox[0].innerHTML);
        console.log(mybox[0].innerHTML);
        }
        
Three sentences in

:

        document.write("<xmp>"+mybox[0].innerHTML+"</xmp>");
        alert(mybox[0].innerHTML);
        console.log(mybox[0].innerHTML);
        

only one sentence can be executed

document.write ("< xmp >"+ mybox [0] .innerHTML +"< / xmp >");

Why are the last two sentences of < xmp > not executed after the execution of document.write ("< xmp >"+ mybox [0] .innerHTML +"< / xmp >")?

        alert(mybox[0].innerHTML);
        console.log(mybox[0].innerHTML);

Mar.14,2021

if you execute document.write, in window.onload, the entire page will be overwritten and all DOM elements no longer exist, so the following mybox [0] cannot be found at all and exits with an exception.


there is no mybox after document.write


Note: because document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which clears the document.


window.onload = function(){
var mybox = document.getElementsByTagName("li");
document.write('<xmp>'+mybox[0].innerHTML+'</xmp>');
alert(mybox[0].innerHTML);
console.log(mybox[0].innerHTML);
}



    window.onload = function(){
    var mybox = document.getElementsByTagName("li");
    alert(mybox[0].innerHTML);
    console.log(mybox[0].innerHTML);
    document.write('<xmp>'+mybox[0].innerHTML+'</xmp>');
    }
Menu