JAVASCRIPT document.write()
JAVASCRIPT
The document.write() method in JavaScript can be used to write content directly to an HTML document during page loading and initialization.
JavaScript document.write() method
➔ The purpose of the document.write() method is to write content to the underlying document body.
➔ If the write() method is invoked during page load, it simply inserts content at that specific point in the document.
➔ If the write() method is invoked by an event, such as a button click event, after the page load, it clears all existing HTML content, i.e. it replaces the previous content of the document.
➔ The document.write() method accepts one or more parameters and can be strings, variables, or HTML code.
➔ This method parses the parameters or expressions and displays them in the document in the order in which they are provided.
Syntax
<script>
document.write(expression1, expression2, ...);
</script>
JavaScript write() during page load
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript document.write() Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
</head>
<body>
<h3>JavaScript document.write() Example</h3>
<p>document.write() during page load</p>
<p>Previous content</p>
<script>
document.write("<p>new content does not replaces previous one.</p>");
</script>
</body>
</html>
Click on the "Try it Now" button to see how it works.
JavaScript write() during page load
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript document.write() Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
</head>
<body>
<h3>JavaScript document.write() Example</h3>
<p>document.write() during page load</p>
<p>Previous content</p>
<script>
document.write("<p style='border: 1px solid red;'>New content");
document.write("does not replaces previous one.</p>");
document.write("<p style='color:red;'>New content does not replaces previous one.</p>");
</script>
</body>
</html>
Click on the "Try it Now" button to see how it works.
JavaScript document.write() after page load.
Example
<!DOCTYPE html>
<html>
<head>
<title>JavaScript document.write() Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<style>
button {
width: 120px;
height: 40px;
}
</style>
</head>
<body>
<h3>JavaScript document.write() Example</h3>
<p>document.write() after page load</p>
<p>Previous content</p>
<button onclick="demo()">call function</button>
<script>
document.write("<p style='border: 1px solid red;'>New content");
document.write("does not replaces previous one.</p>");
document.write("<p style='color:red;'>New content does not replaces previous one.</p>");
function demo() {
document.write("New content replaces previous one");
}
</script>
</body>
</html>
Click on the "Try it Now" button to see how it works.