Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind JS Pyramid in HTML

I created a pyramid using JavaScript and below is the code that I tried so far using for loop:

function showPyramid() {
    var rows = 5;
    var output = '';

    for (var i = 1; i <= rows; i++) { //Outer loop
        for (var j = 1; j <= i; j++) { //Inner loop
            output += '* ';
        }

        console.log(output);
        document.getElementById('result').innerHTML = output;
        output = '';
    }
}

Pretty basic! But I am trying to bind the result with HTML element, say with div as follows:

document.getElementById('result').innerHTML = output;

Instead it shows five stars in a row rather than the format in JS seeing in the console. Anything that I am missing here?

Full Code:

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pyramid</title>
  <script>
    function showPyramid() {
      var rows = 5;
      var output = '';

      for (var i = 1; i <= rows; i++) {
        for (var j = 1; j <= i; j++) {
          output += '* ';
        }

        console.log(output);
        document.getElementById('result').innerHTML = output;
        output = '';
      }
    }
  </script>
</head>

<body onload="showPyramid();">
  <h1>Pyramid</h1>
  <div id="result"></div>
</body>
like image 604
user8512043 Avatar asked Jun 28 '20 13:06

user8512043


2 Answers

Currently, you are resetting the innerHTML at the end of each loop iteration; either use += to append HTML or append all the output together first, then set the innerHTML. Also, you will need to use the <br> tag to create line breaks in HTML.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pyramid</title>
<script>
function showPyramid() {
    var rows = 5;
    var output = '';

    for (var i = 1; i <= rows; i++) {
        for (var j = 1; j <= i; j++) {
            output += '* ';
        }
        output += "<br/>";
    }
    document.getElementById('result').innerHTML += output;
}
</script>
</head>
<body onload="showPyramid();">
<h1>Pyramid</h1>
<div id = "result"></div>
</body>
</html>
like image 161
Unmitigated Avatar answered Oct 16 '22 16:10

Unmitigated


const result = document.querySelector("#result");

function generatePyramid(max = 5) {
  result.innerHTML = "";

  const length = 2 * max - 1;

  for (let i = 1; i <= max; i++) {
    let s = "*".repeat(i).split("").join(" ");

    s = s.padStart(
      s.length + Math.floor((length - s.length) / 2)
    ).padEnd(length);


    const div = document.createElement("div");
    div.innerHTML = s.replace(/\s/g, "&nbsp;");

    result.appendChild(div);
  }
}

// generatePyramid(); // base 5 stars
generatePyramid(11); // base 11 stars
// generatePyramid(21); // base 21 stars
<h1>Pyramid</h1>
<div id="result"></div>
like image 20
Kharel Avatar answered Oct 16 '22 16:10

Kharel