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

Zijun Liao
Zijun Liao
13,409 Points

Hide Up/Button problem

I tried to add a function to refresh the whole list each time when people manipulate it. However, I got the error when I hide the down button on the last item. I really don't know why as I do exactly the same in the previous code,

function refreshList(ul){
  for(let i=1;i<ul.children.length-1;i++){
    ul.children[i].children[0] = 'block';
    ul.children[i].children[1] = 'block';

  ul.firstElementChild.children[0].style.display = 'none';    //Hide the second button of first element.
  ul.lastElementChild.children[1].style.display = "none";    //Error: Cannot read property 'style' of undefined

Sorry for the unformatted code on this page.

Steven Parker
Steven Parker
171,108 Points

To facilitate a complete analysis, make a snapshot of your workspace and post the link to it here.

And when posting code, use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.

2 Answers

Ok, from what I can see the error is referring to the index value, meaning it is not there. This might be because you are subtracting 1 from the length property, but I need to see all the code to know what is really happening. Whenever, you get an error message with 'undefined' it means something is not there or you are accessing it incorrectly.

You're not doing the same because you're trying to access the second element (index 1) of the last element child of the unordered list, not the first. And brian walsh is right, it's likely that there isn't an element that matches that index (i.e. there's only one child element of the last list item).

Also note in your loop you're not actually setting the display CSS property in the style property of the buttons, you're trying to override the elements at those indexes (first and second children of the list items) with the literal string 'block'.