Hopefully someone can help me out here. I'm very new to coding and learning to write my first fizzbuzz. My code works when I execute it using console.log, but when I try to use getElementById.innerHTML it wants to give back random numbers.
Here's what I'm working with:
function clickAlert2() {
for (var i = 1; i <= 140; i++) {
if (i % 3 === 0 && i % 5 === 0) {
document.getElementById("ngList").innerHTML +=
i + ". National Gamers <br>";
} else if (i % 3 === 0) {
document.getElementById("ngList").innerHTML += i + ". National <br>";
} else if (i % 5 === 0) {
document.getElementById("ngList").innerHTML += i + ". Gamers <br>";
} else {
document.getElementById("ngList").innerHTML += i;
}
}
}
.button2 {
background-color: #FAD7A0;
color: #21618C;
text-align: center;
text-decoration: none;
font-size: 18px;
<input type="button" class="button2" value="Print 140 Lines" onclick="clickAlert2()">
<br>
<div id="ngList"></div>
I think it's just something minor, but I have no clue what it could be...
Your code is not giving back random randoms, but rather the i
values which are not divisible by either 3 or 5 (or both) did not receive <br>
newlines in the HTML. If you add a <br>
to the else
case, your input appears what you would expect.
function clickAlert2() {
for (var i=1; i <= 140; i++) {
if (i % 3 === 0 && i % 5 === 0) {
document.getElementById("ngList").innerHTML +=
i + ". National Gamers <br>";
}
else if (i % 3 === 0) {
document.getElementById("ngList").innerHTML += i + ". National <br>";
}
else if (i % 5 === 0) {
document.getElementById("ngList").innerHTML += i + ". Gamers <br>";
}
else {
document.getElementById("ngList").innerHTML += i + "<br>";
}
}
}
.button2 {
background-color: #FAD7A0;
color: #21618C;
text-align: center;
text-decoration: none;
font-size: 18px;
<input type="button" class="button2" value="Print 140 Lines" onclick="clickAlert2()">
<br>
<div id="ngList"></div>
Note sure if you even want to print the non matching lines. If you don't, then the else
condition should be removed entirely.