1

I am trying to use JavaScript to change the HTML contents of the webpage. I have a set of numbers, 0 to 9, and I am trying to use JavaScript to change it from 9 to 0.

The HTML and JS are

function flip(amount) {
  var x = 0;
  for (i = amount; x < amount; x++) {
    setTimeout(() => {
      document.getElementById(String(x)).innerText = String(amount - x - 1);
    }, 2000);
    console.log(x);
  }
}
<span id="0">0</span>
<span id="1">1</span>
<span id="2">2</span>
<span id="3">3</span>
<span id="4">4</span>
<span id="5">5</span>
<span id="6">6</span>
<span id="7">7</span>
<span id="8">8</span>
<span id="9">9</span>
<button id="b1" onclick="flip(10);">Change</button>

In the console, x was logged all ten times correctly. In the console, it said

Uncaught TypeError: Cannot set property 'innerText' of null at change.html:25

(change.html is the name of the document)

I don't know what that's supposed to mean or how I can fix it.

Hooman1130
  • 11
  • 2
  • `for (i = amount; x < amount; x++)` should instead be `for (x; x < amount; x++)` – Rojo Feb 23 '21 at 14:11
  • Add `console.log(x);` inside the setTimeout callback, you'll see '10' printed 10 times. – Jared Smith Feb 23 '21 at 14:11
  • Note that you start your `for` loop with `i = amount`, which creates a global `i` variable set to 10, and then does nothing with it. Either move `var x = 0` in its place, or remove it altogether as in `for (; x < amount; x++)`. – Heretic Monkey Feb 23 '21 at 14:12

1 Answers1

-2

function flip(amount) {
  for (var i = 0; i <= amount; i++) {
    setTimeout(() => {
      document.getElementById(String(x)).innerText = String(amount - i - 1);
    }, 2000);
    console.log(x);
  }
}
<span id="0">0</span>
<span id="1">1</span>
<span id="2">2</span>
<span id="3">3</span>
<span id="4">4</span>
<span id="5">5</span>
<span id="6">6</span>
<span id="7">7</span>
<span id="8">8</span>
<span id="9">9</span>
<button id="b1" onclick="flip(10);">Change</button>
José
  • 32
  • 4
  • Code only answers generally aren't very well received, good answers *explain* how they solve the problem. Since this code just throws an error when you hit the button, it doesn't appear to solve the problem anyway. – Quentin Feb 23 '21 at 22:23