How to increment a div using For JavaScript

2

I'm using this code, but it's not catching. I want to increment with each click on the "Increment" button.

Code:

function incrementar(){
  for (let i =0; i<10; i++){
     document.getElementById("incrementar2").innerHTML = i;
  }
}
<html>
  <body>
  <button onClick="incrementar()">
    Incrementar
  </button>
  <div id="incrementar2"> 0
  </div>
  </body>
</html>

But it's not going at all, it goes straight to number 9. Can anyone help me?

    
asked by anonymous 16.02.2018 / 01:53

1 answer

4

When you use the for repeat structure, you are saying to go from number 0 to 9 (in your case), and with each repetition add the current number in div indicated. As the process is extremely fast, you do not see this update occurring.

As you just want to increment when there is a click action, this for becomes unnecessary. What you should do in this case is to capture the number that is already in div and add up to 1.

const divInc = document.getElementById("incrementar2");

function incrementar(){
  divInc.innerHTML = parseInt(divInc.innerHTML) + 1;
}
<html>
  <body>
  <button onClick="incrementar()">
    Incrementar
  </button>
  <div id="incrementar2"> 0
  </div>
  </body>
</html>

During the process you can not forget to use parseInt . It will serve to transform the contents of div into a numeric value. If you do not use this function, your div will have the following content:

 0 1 1 1 1 1 ...
    
16.02.2018 / 02:18