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 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

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 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>");

Note - If you execute 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 JavaScript document.write()

Since the parameter of document.write() method indicates to 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

JavaScript Online Test


« Previous Tutorial Next Tutorial »