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

155
Visualizações
How to generate a new HTML element each time a JS function is called

I have been working on a webapp that uses steam to log-in through passport and sessions. Lately I have been struggling with finding a good method to create persistent html on the page. Let me explain, here's my index.ejs :

<!DOCTYPE html>
<html lang="en">
<%- include('partials/navbar') %>
<body>
<section id="chat"></section>
<section id="main" style="flexcol center" class="flexcol">
    <button id="newMatch">Create new match</button>
    <div class="match"></div>
</section>
</body>
<script src=".././scripts/jquery.js"></script>
<script src=".././scripts/script.js"></script>
</html>

I have tried to make a js function that inserts a new <div class="match"></div> every time it's called but wasn't successful. Here's the code:

//CONTENT GENERATOR
    let main = document.querySelector('#main');
    let matchDiv = document.createElement('div');
    let matchDivText = document.createElement('h3');
    
    function createMatch(){
        $(matchDivText).append('New match').appendTo($(matchDiv));
        $(matchDiv).addClass('match flex center').appendTo(main);
    };
    
    $('button').click(() => {
        createMatch();
    });

For now, my function is not really working perfectly, It does create a new DIV, append the h2 and add the class but if called multiple times it looks like this(called 3 times) :

n

My question is: How can i make the function create a new DIV each time and also how can I make these DIVS not go away after refresh ?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The problem is that the variables are not in the function, do this:

function createMatch () {
        let main = document.querySelector('#main');
        let matchDiv = document.createElement('div');
        let matchDivText = document.createElement('h3');
        $(matchDivText).append('New match').appendTo($(matchDiv));
        $(matchDiv).addClass('match flex center').appendTo(main);
    };
    
    $('button').click(() => {
        createMatch();
    });
over 4 years ago · Santiago Trujillo 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