Saturday, September 3, 2011

How to use document.write in JavaScript?


Hello guys, Today I am sharing very basic method of javascript which is "document.write()".
Using document.write you can write inside a html document using javascript.

A very basic hello world example is below:

<script type="text/javascript">
document.write("<p>Hello World</p>");
</script>


To understand document.write function in more depth, I am sharing few more simple usage of this function.

<script type="text/javascript">
var sampleText="Sample Example of Document.write function";
document.write("<p>"+sampleText+"</p>");
</script>

Printing date using document.write function:

<script type="text/javascript">
var sampleText="Sample Example of Document.write function";
document.write("<p>"+Date()+"</p>");
</script>


Using document.write function inside a function:

<script type="text/javascript">
function f1() {
document.write('hello world');
}
</script>

<script type="text/javascript">
f1();
document.write('Ba Bye');
</script>


Overriding whole document's content using document.write function:
<script type="text/javascript">
function f1() {
document.write('Some text');//for overwrite entire page content
}
window.onload = w1;
</script>



I hope you like this post. Please share your feedback by commenting below.






No comments:

Post a Comment

Dont SPAM