document.write() is strongly discouraged for new code. It interacts with the HTML parser, can replace the current page when called after loading, and can create injection risks when untrusted HTML is written.The method writes strings into the document stream. It is useful to understand because old JavaScript tutorials and legacy sites may still contain it, but ordinary output should now use DOM APIs.
// Legacy example
document.write("Hello World");
During initial HTML parsing, an inline script can write markup into the current document stream. This is the historical behavior shown by the original Plus2net tutorial.
<script>
document.write("<p>Hello World</p>");
</script>
Do not use this pattern as the normal way to add page content.
For text output, target an element and assign textContent.
const output = document.getElementById("output");
const message = "Hello World";
output.textContent = message;
const paragraph = document.createElement("p");
paragraph.textContent = "Created safely with DOM methods.";
document.body.append(paragraph);
See document.createElement() for more examples.
If your application intentionally creates trusted HTML, use an explicit DOM insertion method and keep untrusted input out of the HTML string. For user-provided plain text, continue to use textContent.
const panel = document.getElementById("panel");
panel.insertAdjacentHTML("beforeend", "<strong>Saved</strong>");
document.writeln() behaves like document.write() but appends a newline character to the document stream. In normal HTML rendering, whitespace is collapsed, so that newline does not automatically produce a visible line break.
// Legacy behavior
document.writeln("Hello World");
document.writeln("Welcome");
The original tutorial demonstrated visible line breaks inside the HTML <pre> element. That is historically correct, but new JavaScript should still update the DOM directly rather than writing the document stream.
addEventListener() and textContent; do not use document.write().const button = document.getElementById("showMessage");
const message = document.getElementById("message");
button.addEventListener("click", () => {
message.textContent = "Hello World";
});
document Object
Cookies
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.