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

Matthew Pelosi
Matthew Pelosi
2,241 Points

removeListItemButtons function

With the following code I've been able to use a conditional statement so that when the list loads the first list item doesn't have an 'up' button and last list item doesn't have a 'down' button. I've been wrestling with a way to create a 'removeListItemButtons' function that would be called after either the 'up','down','remove', or 'add item' buttons are clicked and would cycle through the list, checking if buttons exist on each list item, remove and then add the proper ones depending on the placement of each item in the list. The problem I'm having right now is figuring out how to locate and identify the button elements in each list item and where to place this function in the code.

My brainstorm code is below.

/* function removeListItemButtons(li) { if (li.firstElementChild) { locate list item element and remove '.down' and '.remove' buttons } if (li.lastElementChild) { locate list item element and remove '.up' and '.remove' buttons } } */

1 Answer

Steven Parker
Steven Parker
171,047 Points

I assume you'll create a loop that iterates through the children of the list element (<ul>), and calls this function for each one. You'll probably want to put the loop in its own function since you'll want to call it any time any item is moved or removed. But you won't want to use the "li.firstElementChild" property on the list item itself, but you could use it on the list itself and then compare this particular item to that.

One way to identify the buttons would be by their class names:

    var up = li.querySelector(".up");  // get the "up" button for this list item

Also, your comments talk about removing the "remove" buttons from the first and last items. But isn't it just as legitimate to remove them as items in between?