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

97
Visualizações
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 Respostas
Responde à pergunta

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 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