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...
- add items to array with 'add' button
- render items into their own DIV when I hit 'display'
- 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()">
CodePudding user response:
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);
})