document.write('TEST'); So...">

Document.write error?

Consider a script ..

<html>
<head>
   <script type="text/javascript">
        document.write('TEST');
   </script>
</head>

<body>
    Some body content ...
</body>

</html>

This works great, and the word "TEST" is added to <body>

But when

<script type="text/javascript">
    window.onload = function(){
        document.write('TEST');
    }
</script>

then the contents of the body are completely replaced by the word "TEST", that is, the contents of the old body are deleted, and the word "TEST" is ONLY added.

This only happens when document.writecalled inside a functionwindow.onload

I tried this in chrome. Is there any mistake I made? any suggestions?

+3
source share
4 answers

document.write() , . - -, . DOM innerHTML createElement/createTextNode.

Mozilla:

, document.open(), document.open. , , document.close(), . , , . h1 node .

document.write() HTML, document.open().

DOM:

window.onload = function(){
    var tNode = document.createTextNode("TEST");
    document.body.appendChild(tNode);
}
+9
  • .
  • , - .. (DOM ) , , , .
+1

, document.write() . document.close() document.write(), .

0

, div, div window.onload.

document.write('<div id="afterpostcontent"><\/div>');
window.onload = function()
{
    document.getElementById('afterpostcontent').innerHTML = '<span>TEST<\/span>';
}

JavaScript , :

<script src="afterpostcontentcode.js"></script>
0

Source: https://habr.com/ru/post/1754384/


All Articles