Do you know how and when to use the document.write() method-Javascript

Nikhil
2 min readFeb 8, 2022

What’s up guys. Hope you guys are doing well. This post is all about the javascript document.write() method.

First of all, let’s see what is document.write() in javascript?

Using the document.write() method you can add some text or some HTML elements to your document. Or, you can write some javascript code in your document. Let’s see it with examples.

Example 1 -

<!DOCTYPE html>
<html>
<body>
<h2>This is heading</h2>
<p>This is a paragraph.</p>
<script>
document.write("Hello world!");
</script>
</body>
</html>

The output of the above code :

This is heading

This is a paragraph.

Hello world!

Here you can see we are writing some text directly to the HTML output using document.write() method.

Example 2 -

<!DOCTYPE html>
<html>
<body>
<h1>This is heading</h1>
<script>
document.write("<h2>Hello World!</h2>");
</script>
</body>
</html>

The output of the above code :

This is heading
Hello World!

So, in the first example, we are writing text directly to the HTML output. But in the second example, we have added an HTML element to the document.

Ok, so this all is about document.write() method. But the real question remains the same. And the real question is-

When to use document write()?

You always use this method for testing purposes. And why am I saying this? Because Using document.write() after an HTML document is loaded, will delete all existing HTML. Let’s see with an example.

Example -

<!DOCTYPE html> 
<html>
<body>
<h1>This is heading</h1>
<p>This is a paragraph</p>
<button type="button" onclick="myFunction()">Click me!</button>
<script>
function myFunction() { document.write("Hello World");} </script>
</body>
</html>

Output before clicking the button -

This is heading

This is a paragraph

Click me!

Output after clicking the button-

Hello World

So, after clicking the button, existing HTML got deleted and the output is just the parameter of the document.write() method i.e; Hello World.

Alright, guys, that’s all about today’s topic.

Goodbye.

Originally published at http://developerxon.com on February 8, 2022.

--

--