1

So this my JS code

for (var i=0; i<500; i++) {
  var compare = cryptoSName[i].innerHTML
  if (compare == crypto) {
    document.getElementById("cryptotable" + i).style.color = "#00000"
    document.getElementById('price' + i).innerHTML= "$" + (tradeMsg.message.msg.price.toFixed(4));;
    document.getElementById('perc' + i).innerHTML= tradeMsg.message.msg.perc + "%";
    setTimeout(function() {
      document.getElementById("cryptotable" + i).style.color = "#ff0000"
    }, 500);
  }
}

when I run this, it throws an error saying that cannot read property style of null

Now, If I remove this, It works perfectly fine. What am I doing wrong here? Also, My goal here is to change the color of an element just for few seconds. How can I achieve that? (I was trying to do with setTimeout function)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320

1 Answers1

2

Because you're using var, i is hoisted: to the interpreter, your code actually looks something like this:

var i;
for (i=0; i<500; i++) {
  var compare = cryptoSName[i].innerHTML
  // ...

So at the end of your loop, i has a value of 500, and you don't have an element with an ID of ...500. Use let instead, since let has block scoping and isn't hoisted, unlike var:

for (let i = 0; i<500; i++) {
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320