Problem with DOM manipulation in Loop 1

Hello everyone,
I’m having problem with the DOM manipulation in Loop1. I’m unable to output all element of the array instead its the last element that keeps outputting and I don’t know where I made mistake. Can you please assist me in this. The link to it is;

1 Like

Hi Osbond,
Could you share the code you are using?

sounds to me like you are maybe not building a separate list using ‘li’ and then adding it to the list. Can you check the following

  1. If you do a console log in your look can you generate all the array items on the console?
  2. If this is the case then can you create a new li element and asign it to a variable.
  3. Then can you make what the loop counter is into the text content of this variable.
  4. then can you append this to the list i.e. where it says “let list = document.createElement(‘ul’);”.

Let me know.

Hello Ran,
I was able to solve the problem by following your steps, it seems the list I created was outside for loop block, so when it was moved inside for loop block it worked, but I don’t understand why it worked, can you explain, please this is the link to my code below;

When you has the following outside the loop

let unorder = document.createElement('li');
list.appendChild(unorder);

the actions of the for loop would update the ‘unorder’ variable only once. This would be the last time the loop runs. This is why you see ‘black beans’ the last item in the array.
So effectively the loop does this

i = 0 ==> tomatoes,
i = 1 ==> chick peas,
i = 2 ==> onions,
i ==> 3 ==> rice,
i = 4 ==> black beans, unorder create Li, unoder textcontent ==> i = 4, list append unorder

so effectively you are using the same li and updating the data in it. What should happen is the following

i = 0 ==> tomatoes, unorder create Li, unoder textcontent ==> i = 0, list append unorder
i = 1 ==> chick peas, unorder create Li, unoder textcontent ==> i = 1, list append unorder
i = 2 ==> onions, unorder create Li, unoder textcontent ==> i = 2, list append unorder
i ==> 3 ==> rice, unorder create Li, unoder textcontent ==> i = 3, list append unorder
i = 4 ==> black beans, unorder create Li, unoder textcontent ==> i = 4, list append unorder

so the loop creates a new li for each, adds the text contect of each to the li and appendds it to the list.

Hope that makes sense.

Thanks for taking time out to explain this. I understand its logic now. Keep up the good work

Thats great. Thank you. Keep learning and share any problems you encounter. You are helping me as well to understand by explaining.

3 Likes