JS Code : Version 1
<html> <body> <h1>My First JS Program</h1> <script type="text/javascript"> document.write("<p>" + Date() + "</p>"); </script> </body> </html>
JS Code : Version 2
<html> <body> <h1>My First JS Program</h1> <p id="para1"></p> <script type="text/javascript"> document.getElementById("para1").innerHTML=Date(); </script> </body> </html>
- Both examples produces same visual output.
- Still whenever this script(version 1) is executed it will overwrite complete HTML document .
- Vesrion 2 will overwrite only the tag whose id is specified by DOM method getElementById().
Consider this example -
<html> <body> <h1>My First JS Program</h1> <p id="para1">www.c4learn.com</p> <script type="text/javascript"> document.getElementById("para1").innerHTML=Date(); </script> </body> </html>
Explanation :
- If for a moment we remove JS script from the HTML , www.c4learn.com gets printed inside paragraph (p tag).
- This script used to overwrite p tag always. www.c4learn.com will never be printed.