Document.write is one of the very basic commands in JavaScript. It is used to display some text or values of variables on the screen.
Why Use document.write? Can't we achieve same objective with HTML tags?
HTML text written in <p> tags will always display the text on the screen. JavaScript is dynamic and often needs to make decisions and display messages according to the options selected.For example if the user who submitted a form on our website is a female, so on the next page(confirmation page) JavaScript will display "Thankyou Madam for contacting us, we will get back to you shortly" and a different message if the user was a male "Thank you Sir for contacting us, we will get back to you shortly".
So there needs to be a text displaying command that can go within the javascript code i.e. within <script> </script>tags. That requirement can be fulfilled by a JavaScript specific command and not simple html. Besides simple html cannot output/display the values of variables or compute values of mathematical expressions. That is why document.write command is used.
Syntax
document.write ("text or variable name");
Example 1 - Simple text display and computing Mathematical expressions.

1. In the first code we will display a simple text message on screen.
2. In the second code part, we declared and assigned values to two variables 'a' and 'b' and using the document.write command, put them in a mathematical expression(a+b) to calculate and display the sum of the two variables.
Result
Load the page in browser to see result.

Example 2- Document.write using Variable names and Text Concatenation
In this example we will concatenate(join) some text and a variable name to display them in the browser screen.

We declared a variable, named it nm and assigned it a value "Julie".
We mentioned the variable name in the document.write command. Instead of the variable name, it will display/print the value of the variable on screen.

Example 3- JavaScript document.write - Using HTML tags within JavaScript
We can also include html tags within the quotes " " in the javascript document.write command to modify text formatting(how text is displaye)
. 

The text 'My name is' will be made italic, while the value of variable will be displayed in bold. The proceeding tag is enclosed within <h3> tags so will be displayed in a new paragraph.
Result
writeln- new line after every print
No comments:
Post a Comment
Thank you for your valuable comment