How to use document.write() in JavaScript
The document.write() function is commonly used when testing simple web applications or when learning JavaScript.
document.write() will print the contents of the parameter passed to it to the current node at execution time.
Here is a simple example:
<script>document.write("Some Text")</script>
Here is a more complex example that will demonstrate a major quirk of the document.write() method.
If the DOM tree has already been built, then calling the document.write() method will result in the entire body node of the DOM tree being replaced with whatever parameter is passed to it.
<html>
<head></head>
<body>
<h1>document.write() Demo</h1>
<script>
document.write("<p>This text will appear after h1 tag.</p>")
</script>
<button onclick="writeSomeText();">Pressing This Button Will Cause the Entire DOM Tree To Be Replaced With a Single Node.</button>
<script>
function writeSomeText()
{
document.write("<p>This Text Paragraph Node Replaces The Body of the Document.</p>");
}
</script>
</body>
</html>
Note: Using document.write() in a production environment is frowned upon as the timing of the execution of the function call will determine its behavior. This makes the code much less useful than techniques that would interact with the DOM or use appendChild().
Alternatives to document.write()
The most commonly used alternative is console.log(), which will print the value of the parameter passed to it to the browser’s console, which can be accessed by pressing F12.
Example:
console.log("This text will be printed to the console.")
Another alternative is to use appendChild().
This technique is more complex but adequate for production code, as the output text can be controlled in a consistent manner.
Advanced Example:
<html>
<head></head>
<body>
<h1>document.appendchild() Demo</h1>
<div id="output"></div>
<script>
function demotext() {
var node = document.createElement("P");
var textnode = document.createTextNode("This text will always appears where we want it to.");
node.appendChild(textnode);
document.getElementById("output").appendChild(node);
}
</script>
<h2>Text After the Script</h2>
<button onclick="demotext();">Pressing This Button Will Output Text in a Predictable Way</button>
</body>
</html>
Code Demo:
document.appendchild() Demo
Text After the Script