Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add only new array elements to DOM

Tags:

javascript

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()">
like image 365
nc14 Avatar asked Dec 05 '25 10:12

nc14


1 Answers

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);
})
like image 72
mplungjan Avatar answered Dec 06 '25 22:12

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!