Why is using document.write a bad idea in JavaScript?  Well, document.write is great for debugging or helping you know what a variable is equal to at a certain part in your code.  It’s not a good idea to use on an actual web page especially if you’re not careful.  The reason is it can erase your whole web page.  Here’s an example when document.write can be destructive:

<!DOCTYPE html>
<html lang=””>
<head>
<meta charset=”utf-8″>
<title>Destroyed by document.write</title>
</head>
<body>
Hello<br>
<button id=”click”>Erase the Doc!</button>
</body>
<script>
var btn = document.getElementById(“click”);
btn.addEventListener(“click”,function(){
document.write(“Be gone!”);
})
</script>
</html>

We have a button with the id of “click” that we’ve stored inside a variable called “btn”.  Then we attached an event listener to the button so when you click on it, it will run the anonymous function that uses document.write to put “Be gone!” on the page.  If you load this code up and run it when you click the button, document.write gets rid of everything on the page to write it’s content.  It does this because the content on the page has already been created and when document.write does it’s thing, it overwrites the whole page when inserting the content.  That is one of the main reasons it’s not a good idea to use document.write.

A better alternative is selecting a div on the page and use it’s innerHTML property to put the text.  Here’s an example of that:

<!DOCTYPE html>
<html lang=””>
<head>
<meta charset=”utf-8″>
<title>Saved by innerHTML</title>
</head>
<body>
Hello<br>
<button id=”click”>Print the Text!</button>
<div id=”iamhere”></div>
</body>
<script>
var btn = document.getElementById(“click”);
var d = document.getElementById(“iamhere”);
btn.addEventListener(“click”,function(){
d.innerHTML = “innerHTML saves the page!”;
})
</script>
</html>

In this code we have a div with the id of “iamhere” and we stored that div in a variable called “d”.  When we click the button it goes out to the div and changes it’s innerHTML property to “innerHTML saves the page!” and after it runs, the button and all the content on the page is preserved.  Happy day.  If you want to learn more be sure to check out our JavaScript Training.  Thanks and have an amazing day!