Link to home
Start Free TrialLog in
Avatar of Isabell
Isabell

asked on

document.write() deleting all existing HTML

I am studying javascript now.(I am a beginner).
It says "Using document.write() after an HTML document is fully loaded, will delete all existing HTML"

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

Open in new window


When I run this code, I see the following result.
User generated image
How come I still see existing html? ("My First Web Page" inside <h1> tag and <p> tag)
Avatar of ste5an
ste5an
Flag of Germany image

It's just wrong. write() operates on the document stream. An call after a document is loaded will only result in appending to the existing document.

See document.write() on MDN.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Stefan Hoffman,

From MDN Article (https://developer.mozilla.org/en-US/docs/Web/API/Document/write#wikiArticle)

Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
Avatar of Isabell
Isabell

ASKER

Thank you!