Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!