JS Change HTML Element : getElementById()



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>

Output :
Output of Sample Java Script Program
Explanation :

  1. Both examples produces same visual output.
  2. Still whenever this script(version 1) is executed it will overwrite complete HTML document .
  3. 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 :

  1. If for a moment we remove JS script from the HTML , www.c4learn.com gets printed inside paragraph (p tag).
  2. This script used to overwrite p tag always. www.c4learn.com will never be printed.