JavaScript JavaScript and the DOM 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.

Ryan Groom
Ryan Groom
17,287 Points

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

Ryan Groom
Ryan Groom
17,287 Points

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!

Ryan Groom
Ryan Groom
17,287 Points

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