innerHTML does not work completely

Asked

Viewed 110 times

0

Hello, I would like a help to run a code. The challenge was to print numbers from position 0 through 15 of the array and tell which are even and which are odd. It works perfectly on the.log console, but it’s not working Document. I’ll put the part in JS and HTML for better understanding.

var nums = [1, 6, 3, 5, 8, 3, 245, 63, 87, 342, 68, 348, 1002, 14, 7, 12];
function remainder(x){
  for(var i=0;i<x.length;i++){
    if(x[i]%2==1){
      document.getElementById("msg"+1).innerHTML = x[i]+" is ODD.";
    }else{
      document.getElementById("msg"+1).innerHTML = x[i]+" is EVEN.";
    }
  }
}
remainder(nums);
<p id="msg1"></p>
<p id="msg2"></p>
<p id="msg3"></p>
<p id="msg4"></p>
<p id="msg5"></p>
<p id="msg6"></p>
<p id="msg7"></p>
<p id="msg8"></p>
<p id="msg9"></p>
<p id="msg10"></p>
<p id="msg11"></p>
<p id="msg12"></p>
<p id="msg13"></p>
<p id="msg14"></p>
<p id="msg15"></p>
<p id="msg16"></p>

1 answer

2

You’re using .getElementById("msg" + 1)... ie you are always rewriting the same element. You should use the i to add this number. But taking into account that the i begins in 0 you have to add +1. That is to say:

document.getElementById("msg" + (i + 1))

Example:

var nums = [1, 6, 3, 5, 8, 3, 245, 63, 87, 342, 68, 348, 1002, 14, 7, 12];

function remainder(x) {
  for (var i = 0; i < x.length; i++) {
    if (x[i] % 2 == 1) {
      document.getElementById("msg" + (i + 1)).innerHTML = x[i] + " is ODD.";
    } else {
      document.getElementById("msg" + (i + 1)).innerHTML = x[i] + " is EVEN.";
    }
  }
}
remainder(nums);
<p id="msg1"></p>
<p id="msg2"></p>
<p id="msg3"></p>
<p id="msg4"></p>
<p id="msg5"></p>
<p id="msg6"></p>
<p id="msg7"></p>
<p id="msg8"></p>
<p id="msg9"></p>
<p id="msg10"></p>
<p id="msg11"></p>
<p id="msg12"></p>
<p id="msg13"></p>
<p id="msg14"></p>
<p id="msg15"></p>
<p id="msg16"></p>

Browser other questions tagged

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