Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to appendChild to every list item? for now it only appendChild to last list item.

// append upBtn to all exist list items

const upBtn = document.createElement("button");  
upBtn.className ='up';  
upBtn.textContent = "up";  

const lis = document.querySelectorAll("li");  
for (var i = 0; i < lis.length; i++) {  
    lis[i].appendChild(upBtn);  
}

1 Answer

Steven Parker
Steven Parker
243,656 Points

You're trying to append the same element more than once. An element can only appear in one place in the DOM tree. When you append an existing item to a new location, it moves from where it used to be to the new location.

My guess is that what you really want to do is create a new element for each list item, and then append it. So the call to createElement would need to be inside the loop.

Thank you so much for the help!!