JavaScript JavaScript and the DOM Traversing the DOM Getting the First and Last Child

Pat Cranfill
Pat Cranfill
5,899 Points

How can I continuously update the DOM with challenge at the end of the video?

I have tried several different ways to continuously update the DOM to be able to remove the up and down buttons for the first and last item. I've done it in a function, calling it after initial buttons are created and at the end of the JS file - no luck. I've tried changing the display value to 'none' in a for loop with conditional statement - no luck. I've tried removeChild for that button on that specific list item - no luck. I haven't figured out how to keep the update happening when moving other items up and down the list.

Here's a snapshot of what I have left after deleting a lot of code that didn't work. Only have left a loop that removes the button from the first list item:


1 Answer

Birthe Vandermeeren
Birthe Vandermeeren
17,139 Points

I don't know if you're still looking for an answer, but in case you are, here's my experience:

First off, you don't need a loop to remove that child, as you know you want to remove the first child, so you can just select it immediately instead of an "if (i==0)". I'd just create another function outside the loop, to remove the up button from the first list item and the down button from the last.

But before we go any further, it's easier to not remove the button, but just set the visibility to "hidden" (CSS, so you need the .style attribute), so you can easily set it back to "visible" when that list item is no longer the first or last item in the list.

To have the buttons update every time something changes in the list, I'm calling that function after all buttons are created, at the end of the listUl.addEventListener, so it refreshes the hidden buttons when one of the up, down or remove buttons is clicked, and at the end of the addItemButton.addEventListener, so it refreshes when an item is added to the list.

I'm adding my solution to the forum, if you're interested in checking it out.