Use of <div> in setInterval() code

<!DOCTYPE html>
      <title>Javascript Interval</title>
      <h1>Javascript Interval function</h1>
      <button onclick="start_timer()">Start Timer</button>
      <div id="counter"></div>
      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;

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

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 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