Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Understanding the document.write() Method
3.
Syntax of JavaScript Document.write()
4.
How does document.write work?
5.
A Basic Example of document.write() in JavaScript
6.
Key Points to Remember About document.write()
7.
Parameters of JavaScript Document.write()
8.
Return Value of JavaScript Document. write()
9.
Exceptions of JavaScript Document.write()
10.
Document.writeln vs document.write in JavaScript
11.
Frequently Asked Questions
11.1.
Can document.write() be used to add content after a page has loaded?
11.2.
Can document.write() be used with HTML tags?
11.3.
Is document.write() suitable for production code?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

JavaScript Document.write()

Author Gunjan Batra
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

In the vast world of JavaScript, there are numerous methods designed to manipulate and manage web content. One such method, often encountered by beginners, is the document.write() method. This built-in JavaScript method is frequently used for testing and learning, but it has its limitations and appropriate use cases in more complex web development.

Javascript Document.write()

 Let's dive deeper into the document.write() method, its usage, and its role in JavaScript programming.

Understanding the document.write() Method

The document.write() method is used to write a string of text to a document's stream opened by document.open(). Here is the simple syntax:

document.write(text)

The text parameter is the string of text or HTML to be written into the document. The string can contain HTML tags, allowing for the creation of dynamic HTML content.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax of JavaScript Document.write()

Here's the basic syntax of document.write():

document.write(expression);

 

expression is the content you want to write to the document. This can be a string, variable, HTML code, or any valid JavaScript expression.

How does document.write work?

The document.write() method in JavaScript is used to write content to a document, typically an HTML document. When you use document.write(), it dynamically adds content to the HTML document as it is being parsed by the browser. These are the steps that shows how document.write() works:

1. Parsing HTML: When a web page is loaded, the browser parses the HTML document from top to bottom.

2. Encounter document.write(): When the browser encounters a document.write() statement during the parsing process, it executes the JavaScript code associated with it.

3. Writing Content to the Document: The content specified as the argument to document.write() is then written to the document at the current position in the HTML. This content can be a string, a variable, or any valid JavaScript expression.

document.write("Hello, World!");

 

In this example, the string "Hello, World!" would be written to the document where the document.write() statement is located in the HTML.

4. Overwriting Existing Content: If document.write() is called after the HTML document has fully loaded, it will overwrite the entire content of the document. This is important to note because it means any existing HTML content, including the HTML, head, and body elements, will be replaced.

document.write("<h1>New Heading</h1>");

 

In this case, if called after the document has loaded, it would replace the entire document with just the new heading.

5. Execution Order: The order of execution matters. If you have multiple document.write() statements, the content will be written in the order the statements are encountered during the parsing process.

A Basic Example of document.write() in JavaScript

Here's a straightforward example to illustrate how the document.write() method works:

<!DOCTYPE html>
<html>
<body>
<script>
document.write("<h1>Welcome to JavaScript Programming!</h1>");
</script>
</body>
</html>

Output

output

In this HTML file, we use document.write() within a script tag to write a heading into the body of our HTML document. The heading reads "Welcome to JavaScript Programming!" and is enclosed within h1 tags, making it a level one heading.

Key Points to Remember About document.write()

There are a few critical considerations about document.write():

  • Timing: If you call document.write() after the page has finished loading, it will overwrite the entire document, hence, it's typically used for immediate writing during page load.
     
  • Not for production: It's generally considered a bad practice to use document.write() in production code due to its potentially destructive behavior.
     
  • Alternatives: Methods like innerHTML and the DOM manipulation methods (like createElement(), append(), etc.) are typically preferred for adding content to an HTML document in more complex scenarios.

Parameters of JavaScript Document.write()

The document.write() method accepts one or more parameters, which can be of various types:

1. String:

document.write("Hello, World!");

 

The string you want to write to the document.
 

2. Variables:

var message = "Hello, World!";
document.write(message);

 

You can pass variables or expressions as parameters.
 

3. HTML Code:

document.write("<h1>This is a heading</h1>");

 

HTML code can be included as a parameter, and it will be written to the document.

Return Value of JavaScript Document. write()

Unlike many other JavaScript methods, document.write() does not return a value. Its primary purpose is to write content to the document dynamically. When used, it directly manipulates the HTML content of the document rather than returning a value.

Exceptions of JavaScript Document.write()

While using document.write() in JavaScript, there are several considerations and potential exceptions to be aware of:

1. Timing Issues

Document Loaded: If document.write() is used after the HTML document has fully loaded (i.e., after the DOMContentLoaded event), it will overwrite the entire content of the document. This behavior might lead to unexpected results.
 

2. Document Parsing

Parsing in Progress: If the HTML document is still being parsed by the browser, using document.write() will add content at the current position in the HTML. However, this can result in a delayed rendering of the page.
 

3. Async Loading

Asynchronous Loading: In modern web development, scripts are often loaded asynchronously. If document.write() is used in an asynchronously loaded script, it may not behave as expected, especially if the document has already finished loading.
 

4. Security Risks

Cross-Site Scripting (XSS): Using document.write() with untrusted or user-supplied content can pose a security risk by opening the door to Cross-Site Scripting (XSS) attacks. It's important to properly sanitize and validate any content that is dynamically written to the document.
 

5. Maintenance Challenges

Code Maintainability: Overreliance on document.write() can lead to code that is difficult to maintain and understand. In modern web development, manipulating the DOM directly or using frameworks like React or Vue is often preferred.
 

6. Limited Use Cases

Limited Use in Modern Development: With the advent of more sophisticated web development practices and frameworks, the use of document.write() has become less common. Modern applications often utilize more controlled ways to manipulate the DOM and manage dynamic content.

Document.writeln vs document.write in JavaScript

Feature document.write document.writeln
Purpose Writes content to the document dynamically. Similar to document.write, but appends a newline (\n) after each call.
Usage document.write(expression); document.writeln(expression);
Newline Character Does not automatically add a newline character. Automatically appends a newline character after each call.
Overwriting Content Overwrites the entire document if called after the document has fully loaded. Same as document.write - overwrites the entire document if called after the document has fully loaded.
Example javascript document.write("Hello, World!"); javascript document.writeln("Hello, World!");
Effect on Existing Content Can overwrite the entire content of the document if used after the document has loaded. Similar to document.write, can overwrite the entire content of the document if used after the document has loaded.
Additional Considerations Can be more challenging to use in modern web development due to its potential side effects. Similar considerations as document.write - use with caution, especially in modern applications.

Frequently Asked Questions

Can document.write() be used to add content after a page has loaded?

While technically possible, it's not advised, as it will overwrite the entire document.

Can document.write() be used with HTML tags?

Yes, you can include HTML tags in the text passed to document.write(), allowing you to create dynamic HTML content.

Is document.write() suitable for production code?

It's generally considered bad practice to use document.write() in production due to its potential to overwrite entire documents and its blocking nature.

Conclusion

JavaScript's document.write() method can be a handy tool, especially for beginners, for immediate text output during page loading. However, its potential to overwrite entire documents and its blocking nature has led to it being generally discouraged for use in production code. For more complex and safer content manipulation, JavaScript provides other methods like innerHTML and a variety of DOM manipulation methods. It's vital to understand the strengths and weaknesses of these tools to choose the right one for your coding tasks.

To learn more about this topic, check out the link below

Previous article
Special Arrays in JavaScript
Next article
How to Read *.CSV File in JavaScript?
Live masterclass