Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

96
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda