FizzBuzz Javascript in html

so I'm doing this FizzBuzz challenge and I've made a mistake but cannot identify it. I'm wanting numbers from 1-100 to display on a web browser. The numbers that are divisible by 3 should say "fizz", the numbers divisible by 5 should say "buzz", and the numbers divisible by both 5and3 should say "FizzBuzz." I'm unable to get the browser to display the words, and for some reason it only displays the numbers.

function fizzbuzz() {
  var display = document.getElementById('display');
  var displayHTML = "";

  for (i = 1; i < 101; i++) {
    if (i % 3 === 0 && i % 5 === 0) {
      console.log("FizzBuzz")
    } else if (i % 5 === 0) {
      console.log("buzz")
    } else if (i % 3 === 0) {
      console.log("Fizz")
    } else {
      console.log(i)
    }


    displayHTML += "<p>" + i + "</p>";
  }
  display.innerHTML = displayHTML
}
<body onload="fizzbuzz()">
  <div id="display">

  </div>
</body>

2 answers

  • answered 2020-07-05 03:21 Tushar

    That's because you are concatenating i, the counter to displayHTML here displayHTML += "<p>" + i + "</p>";

    Instead save the value you want to print in a variable on conditional check and then concatenate it afterwards

    var result = '';
    for (i = 1; i < 101; i++) {
        if (i % 3 === 0 && i % 5 === 0) {
          result = "FizzBuzz";
        } else if (i % 5 === 0) {
          result = "buzz";
        } else if (i % 3 === 0) {
          result = "Fizz";
        } else {
          result = i;
        }
    
    
        displayHTML += "<p>" + result + "</p>";
    

  • answered 2020-07-05 03:30 sonEtLumiere

    When a condition is true, you can set the result in a variable and then print your displayHTML element.

    function fizzbuzz() {
      var display = document.getElementById('display');
      var divisible = "";
      var displayHTML = "";
    
      for (i = 1; i < 101; i++) {
        if (i % 3 === 0 && i % 5 === 0) {
          divisible = "FizzBuzz";
        } else if (i % 5 === 0) {
          divisible = "Buzz";
        } else if (i % 3 === 0) {
          divisible = "Fizz";
        } else {
          divisible = "";
        }
    
        displayHTML += "<p>" + i + ":" + divisible + "</p>";
      }
      display.insertAdjacentHTML('afterend', displayHTML); 
    }
    
    fizzbuzz();