How to increment a div using For Javascript

Asked

Viewed 244 times

2

I’m with this code but it’s not picking up. I want to increment every click on "Increment".

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 is not going at all, it goes straight to number 9. Someone can help me ?

  • Can make a table test of your code?

  • Either replace the number by intervals or add content?

  • @Rpgboss add to the content. Example, the number ta 0, when I click the button, it go pro 1 and so on.

  • Now I understand, but @Valdeir Psr has posted the solution and explanation.

1 answer

4


When you use the repeating structure for, you are saying to go from number 0 to 9 (in your case), and to each repeat add the current number in the 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 the div and add with 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 the parseInt. It will serve to transform the content of div a numerical value. If you do not use this function, its div will have the following content:

 0 1 1 1 1 1 ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.