2

I'm using the old FizzBuzz exercise, and utilizing textContent, trying to load a page with each of the values listed one after the other, vertically. Right now I'm getting this instead:

12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzz1617Fizz19BuzzFizz2223FizzBuzz26Fizz2829FizzBuzz3132Fizz34BuzzFizz3738FizzBuzz41Fizz4344FizzBuzz4647Fizz49BuzzFizz5253FizzBuzz56Fizz5859FizzBuzz6162Fizz64BuzzFizz6768FizzBuzz71Fizz7374FizzBuzz7677Fizz79BuzzFizz8283FizzBuzz86Fizz8889FizzBuzz9192Fizz94BuzzFizz9798FizzBuzz

Here is my code:

var n = 1, str = ""

while (n <= 100) {
  if (n % 3 === 0 && n % 5 === 0) {
    str = str + "FizzBuzz"
  } else if (n % 3 === 0) {
    str = str + "Fizz"
  } else if (n % 5 === 0) {
    str = str + "Buzz"
  }
  else {
    str = str + n
  }
  n++
}

document.querySelector(".container").textContent = str
<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <p class="container"></p>
</body>
</html>
cdlane
  • 40,441
  • 5
  • 32
  • 81
  • 1
    Could it be as simple as appending a line break to each "Fizz", "Buzz", "FizzBuzz", or number? – shoover Jul 17 '15 at 22:45

1 Answers1

1

Don't use textContent, since it doesn't include any formatting. Use innerHTML and put <br> tags after each item.

var n = 1, str = ""

while (n <= 100) {
  if (n % 3 === 0 && n % 5 === 0) {
    str = str + "FizzBuzz<br>";
  } else if (n % 3 === 0) {
    str = str + "Fizz<br>";
  } else if (n % 5 === 0) {
    str = str + "Buzz<br>";
  }
  else {
    str = str + n + '<br>';
  }
  n++;
}

document.querySelector(".container").innerHTML = str
<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <p class="container"></p>
</body>
</html>
Barmar
  • 741,623
  • 53
  • 500
  • 612