Skip to content

Document write JavaScript | Method

  • by

The document write() method writes directly to an open (HTML) document stream in JavaScript. When document.write() is executed, after the page loads it will erase all the contents of the web page and only show the text inside it.

write(markup)
// example
document.write("I am new text");

Warning: The use of the document.write() method is strongly discouraged.

Document write JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    document.write("Hello World!");
  </script>

  <h2>The Lorem Ipsum Passage</h2>
  <p>This is Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

</body>
</html>

Output:

Document write JavaScript

Using document.write() after a document is loaded, deletes all existing HTML:

// This should be avoided:
function myFunction() {
  document.write("Hello World!");
} 

Difference Between write() and writeln()

The writeln( ) method is only useful when writing to text documents (type=”.txt”) otherwise avoid it. With this method, Newline characters are ignored in HTML.

document.write("Hello World!");
document.write("Have a nice day!");
document.write("<br>");
document.writeln("Hello World!");
document.writeln("Have a nice day!");

Do comment if you have any doubts or suggestions on this JS document topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *