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

95
Views
Add only new array elements to DOM

I'm making a to do list style app but I'm stuck on how to only create DOM elements only from new elements that get added to an array and will keep rendering the same element n times if you re-click the button.

I have a simple HTML form which creates a title for a new 'Snippet' object.

Then I add these to an array like this

function addSnippetToArray() {
    
    let snippetTitle = document.getElementById('snippetTitle').value;
    let snippetToAdd = new Snippet(snippetTitle);
    snippetsArray.push(snippetToAdd);
    console.log(snippetsArray);
}

Then I'm trying to render these into their own DIV's using a form button like this...

function displaySnippets() {

    let container = document.getElementById('container');
    let newCard = document.createElement('div');
    snippetsArray.forEach(function (snip) {
    newCard.textContent = snip.title;
    container.appendChild(newCard);

    })
}

What I don't understand is that when I call displaySnippets() at the end of the addSnippetsToArray() function, it seems to work fine.

But if I just call displaySnippets() using its own button it only renders the last element in the array and keeps rendering it multiple times if you click the button again.

What I'm trying to do is...

  1. add items to array with 'add' button
  2. render items into their own DIV when I hit 'display'
  3. only add new items to the DOM that aren't already there (I thought best to do this without clearing the whole thing and redrawing everything if only 1 element is being added?)

I'm calling the functions from the button like this :

<input type="button" value="Add snippet" onclick="addSnippetToArray()">
<input type= "button" value="Display" onclick="displaySnippets()">
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to create new divs for each and empty the container before looping

 const container = document.getElementById('container');
 container.innerHTML = ""; // clear
 snippetsArray.forEach(function (snip) {
  let newCard = document.createElement('div');
  newCard.textContent = snip.title;
  container.appendChild(newCard);
})
about 4 years ago · Juan Pablo Isaza 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!