LOTUSMS LOTUSMS - 22 days ago 11
Javascript Question

Displaying my console.log on the screen

I have a javascript that prints out all prime numbers 1 - 100, and I am using innerHTML to printout the results. My console is giving me the list of numbers but the innerHTML is giving me a single number. 100 I think. How can I display the list of numbers same way I am printing in my console but inside a div of ID="prime"?

Here is what I wrote

for (var i = 1; i <= 100; i++) {
var invalid = false;

for (var j = 2; j <= i; j++) {

if (i % j===0 && j !== i) {
invalid = true;
}
}

if (invalid === false) {
console.log(i);
}
}
document.getElementById('prime').innerHTML = i;


My Div

<div id="prime"> </div>


My Console ouputs 1, 2, 3, 5, 7, 11, ...97 but my div outputs 101

Here is a CODEPEN

thanks

Answer

Your placement of the code is wrong. For starters, put it like so:

 if (invalid === false) {
    console.log(i);
    document.getElementById('prime').innerHTML = i;
}

Also, if you use that code, it'll only display the last value of i. To fix that, use += instead of =

if (invalid === false) {
    console.log(i);
    document.getElementById('prime').innerHTML += i + " | ";
}

Finally, I'd add a line (" | ") behind the i, to make the number sepetations clear.

Comments