I’m having trouble accessing an array, and looping through the array then printing the elements inside the array to the DOM. For some reason, it just print’s only "Relish" and it doesn’t print the two other elements inside the array "Ketchup" and "Mustard". Is there anyway I can get a hint on how to accomplish this task?
Here is my code bellow.
let topingsCount;
const burger = document.createElement('div');
const topingsDiv = document.createElement('div');
const condiments = ['Ketchup', 'Mustard', 'Relish']
const condimentsNewDiv = document.createElement('div');
function createBuger(condiments){
burger.className = 'burger';
burger.appendChild(topingsDiv)
topingsDiv.className = "topings";
condimentsNewDiv.className = "condiments";
topingsDiv.appendChild(condimentsNewDiv)
for(let topingsCount = 0; topingsCount != condiments.length ; topingsCount++){
topingsDiv.appendChild(condimentsNewDiv).textContent = condiments[topingsCount];
console.log(condimentsNewDiv);
}
console.log(burger);
document.body.appendChild(burger)
}
createBuger(condiments);
I tried a console.log(condimentsNewDiv); inside the for loop so, I can print out each condiment. But it only printed out relish <div class="condiments">Relish</div>
3X times. I was expecting for it to print out:
<div class="condiments">Ketchup</div>
<div class="condiments">Mustard</div>
<div class="condiments">Relish</div>
2
Answers
It looks like you are using condimentsNewDiv every time rather than creating a new div for each condiment. This will reuse the same element reference over and over for each condiment, which means it’s likely just overwriting the textContent each time.
Try doing something like this instead:
Notice here we are creating a new div for each condiment rather than reusing the same one over and over.
Here is the working example: