Use of <div> in setInterval() code

<!DOCTYPE html>
<html>
   <head>
      <title>Javascript Interval</title>
   </head>
   <body>
      <h1>Javascript Interval function</h1>
      <button onclick="start_timer()">Start Timer</button>
      <br>
      <div id="counter"></div>
   </body>
   <script>
      var counter = 0;
      function start_timer(){
        setInterval(increment_counter, 1000);
      }
      
      function  increment_counter() {
        counter_element = document.getElementById("counter");
        counter_element.innerHTML = counter;
        counter = counter + 1;
      }
   </script>
</html>

In this above code, what is the use of div? I did not understand why we had to use div and is there any alternative to using div? Please explain!

  1. In the above code, div is used to show the counter value. Check here what is div https://www.w3schools.com/tags/tag_div.asp

We are showing the counter value of inside the div. Check the below line, we are getting the div element using the id of div

ounter_element = document.getElementById("counter");

Then we are setting the counter value inside the div.

ounter_element.innerHTML = counter;

Check this link https://www.w3schools.com/jsref/met_document_getelementbyid.asp to know more about the getElementById

  1. Yes, you can use other HTML elements instead of div. For example, You can use <span>, <section>, <h1> , <h2> etc. Check the below example.
 <span id="counter"></span>
1 Like