JavaScript document.write()

The JavaScript document.write() method is used to write text to an opened HTML document. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <h2>The document.write() Method</h2>
   
   <script>
      document.write("Hi there!");
   </script>
   
</body>
</html>
Output

The document.write() Method

JavaScript document.write() syntax

The syntax of the document.write() method in JavaScript is:

document.write(markup)

The markup refers to a string that contains the text to write to the document.

JavaScript document.write() example

Consider the following code as an example demonstrating the "document.write()" method in JavaScript:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <script>
      document.write("<h2>The write() Method</h2>");
      document.write("<p>This is an example of write() method.</p>");
   </script>
   
</body>
</html>
Output

In the above example, the two JavaScript statements can also be wrapped with one, in this way:

document.write("<h2>The write() Method</h2><p>This is an example of write() method.</p>");

Warning: If you execute the document.write() method in any way, after loading the document. Then all HTML will be deleted. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>This is para one</p>
   <p>This is para two</p>
   <button onclick="myFunction()">Click Me to Execute document.write()</button>
   <script>
      function myFunction() {
         document.write("Welcome!");
      }
   </script>
   
</body>
</html>
Output

This is para one

This is para two

Now if you click on the button, Click Me to Execute document.write(), then the whole HTML will be removed.

Break line in the JavaScript document.write()

Since the parameters of the document.write() method indicates markup. Therefore, writing the BR tag gives you the line break. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <script>
      document.write("Hello<BR>there!");
   </script>
   
</body>
</html>
Output

Advantages of the document.write() function in JavaScript

Disadvantages of the document.write() function in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!