Reputation: 4454
I red this:
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
So I decided to test this, I wrote this code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>I'm TEST which should be a deleted?</p>
<script>
var drink = "Red bull";
var lyrics = "";
var cans = 99;
while(cans > 0)
{
lyrics += cans + " cans of " + drink + " on the wall <br>";
cans--;
}
document.write(lyrics);
</script>
</body>
</html>
As you can see I added <p>I'm TEST which should be a deleted?</p>
after that I invoked document.write
between my script
tag which should delete all existing html including this paragraph?
But output is next:
But paragraph is still there, shouldn't it be removed by following this sentence:
If it is used after an HTML document is fully loaded, it will delete all existing HTML.
Upvotes: 3
Views: 1895
Reputation: 317
Test it with this code. You will get to know what document.write() actually do. Upon clicking the button the HTML will get hide and you will only see the 11(document.write(5+6)) answer. This is what "The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML." means.
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try it</button>
</body>
</html>
Upvotes: 0
Reputation: 131436
document.write(lyrics);
is invoked during the loading of the page.
Declare it in a function :
<script>
function writeData(){
document.write(lyrics);
}
</script>
and invoke the function at a time where the document was fully loaded
and you should see another behavior.
For example with a button click :
<button onclick="writeData()">WriteData</button>
Upvotes: 5
Reputation: 158
You basically answered it yourself
after an HTML document is fully loaded
If you test it with a timeout, you will see that it will replace the paragraph (note: this is just an example, you should definitely not approach a forced load like this if it's a needed function)
setTimeout(function() {
while(cans > 0)
{
lyrics += cans + " cans of " + drink + " on the wall <br>";
cans--;
}
document.write(lyrics);
}, 2000);
Upvotes: 2
Reputation: 723944
The document isn't yet done loading when the script is running because the script is not at the end of the document (after the </html>
end tag).
document.write()
will only erase the existing contents when run after all the markup has been processed, either in a console or in an event handler fired after the fact.
Upvotes: 3