0

I have an element with of "0" and I want to be able to iterate this with a button such that the value goes up by 1 each time.

Here's the code:

HTML:


<head>
  <div class = "contents">
  <h1 id = "e1">0</h1>
   <button id = "iterate" type = "button"  >+1</button>
  </div>
    </head>

CSS:

h1, #iterate {

  padding: 100px;
  font-size:400px;
  display: inline;
}

.contents {
  text-align: center;
}

JS:

**document.getElementById("iterate").onclick = function() {
  let a = document.getElementById("e1").innerHTML;
  console.log(a);
  a = a + 1;
  document.getElementById("e1").innerHTML = a;
  
}**

This keeps adding the string "1" to the document. I suspect because the html element is of type string so the string of "1" is being concatenated.

How can I have an integer type displayed on my document?

  • 1
    Convert it to a number: `let a = parseInt(document.getElementById("e1").innerHTML);` – Barmar Mar 07 '23 at 22:30
  • 1
    FYI, that's not what "iterate" means. Iteration is looping, e.g. `for` or `while`. The word for this is "increment". – Barmar Mar 07 '23 at 22:31
  • Turn a into a number before adding one `a = Number(a) + 1` or `a = +a + 1` – jjj Mar 07 '23 at 22:34

0 Answers0