Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
How can I print a function from JavaScript to html

I'm trying to make a out of '*' and I got the code right because it works in the console but when I try to print it in the html document it does not work

function Pyramid() {
    let rows = 9;
    let output = '';
    for (let i = 1; i <= rows; i++) {
        for (let j = 1; j <= i; j++) {
            output += '*  ';
        }
        console.log(output);
        return output;
        output = '';
    }
}
document.getElementById('pyramid').textContent = generatePyramid();
<body>
    <div id="pyramid"></div>
    <script src="../script.js/script.js"></script>
</body>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try this

document.getElementById("pyramid").innerHTML='generatePyramid()';

about 4 years ago · Juan Pablo Isaza Relatório

0

Okay, so there are a few minor issues here.

  • Your function is called Pyramid but you are calling generatePyramid.
  • You are returning at the end of the first row because return output is within the for loop.
  • In the console you are outputting using console.log which will give you a row in the console... however for the HTML you are just dumping it all so it would be a continuous row of stars instead of one row at a time.

In the code below I've fixed these issues and made it so it outputs each row in a <p>. There are numerous ways to achieve this result and improve upon it, but I think this is what you were aiming for.

function generatePyramid() {
  let rows = 9;
  let output = "";
  for (let i = 1; i <= rows; i++) {
    output += "<p>";
    for (let j = 1; j <= i; j++) {
      output += "* ";
    }
    output += "</p>";
  }
  return output;
}

document.getElementById("pyramid").innerHTML = generatePyramid();

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda