Reputation: 79
fruitsButton.addEventListener("click", function () {
fruitsArray.forEach((fruit) => {
newParagraph.innerText = `I'll buy a ${fruit} next year `;
screenToShow.append(newParagraph);
});
});
I want my code to loop each individual element and show the text but when i try doing it keeps showing just the last element of the array, i tried to using the console and it works but on DOM it does not really work so pls help
Upvotes: 2
Views: 197
Reputation: 2642
You are using the same newParagraph
every time, replacing the current innerText instead of adding a new paragraph.
You can create a new p
element for every fruit in the loop:
const screenToShow = document.getElementById('screen')
const fruitsArray = ['apple', 'banana', 'cranberry']
fruitsArray.forEach(fruit => {
const newParagraph = document.createElement('p')
newParagraph.innerText = `I'll buy a ${fruit} next year`
screenToShow.append(newParagraph)
})
<div id='screen'></div>
Upvotes: 1
Reputation: 19
newParagraph.innerText += I'll buy a ${fruit} next year
Add += to append multiple elements see my addition above
Upvotes: 1