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 JavaScript and the DOM (Retiring) Traversing the DOM Getting the First and Last Child

O V
O V
2,483 Points

Why index numbers of <li> do not update after DOM manipulation?

Consider the following:

<ul> <li>grapes</li> // Index 0 <li>amethyst</li> // Index 1 <li>lavender</li> // Index 2 <li>plums</li> // Index 3 </ul>

With DOM manipulation, I re-order the list items and they display correctly in the browser. <ul> <li>lavender</li> // Index 2
<li>amethyst</li> // Index 1 <li>grapes</li> // Index 0 <li>plums</li> // Index 3 </ul>

However, when I log the firstElementChild of <ul> , I would expect the console to return <li>lavender</li>. Instead, it keeps returning <li>grapes</li>. Likewise, if I log the item using index [0].

Why is the index number following the list item after re-ordering the list?

How can I repopulate the list so that firstElementChild of <ul> , or index[0] ALWAYS shows the current first item on the list after DOM manipulation.

O V I'm not having the same issue. Mine showed the updated item when I used the buttons to swap the list around. Can you show me the console log code you're running? Also when you say "after DOM manipulation" do you mean after you press the buttons that reorder the list in the exercise?

O V
O V
2,483 Points

Ryan Groom

since we had created

const firstListItem = listUl.firstElementChild;

In the console I'm running:

firstListItem

1 Answer

O V So I believe the issue is that you are console logging a variable. As soon as your page loaded up, the value stored in the variable "firstListItem" was set to the actual value of the original first list item. Rearranging the order of the elements with the button has no tie to actually changing the value assigned to that variable. If you changed the order of list items and instead console logged listUI.firstElementChild I believe it should behave accordingly. Let me know if this works and answers your question. If not, feel free to comment back!

O V
O V
2,483 Points

Thank you. I believe you're right, I tried logging list[0] and it worked. I was thinking earlier about it and the idea of variable storage vaguely crossed my mind. I'm glad you confirmed it!

O V Sure, let me know if anymore questions come into mind. I check Treehouse daily.