JavaScript JavaScript and the DOM Traversing the DOM Using parentNode to Traverse Up the DOM

Rochelle Burrows
Rochelle Burrows
8,232 Points

Calling 'parentNode' on list item returns 'null'.

Hi everyone,

I'm not sure what's happening with my code; I'm trying to make the 'up' button in my app work, but when I call the 'parentNode' property on the 'li' element, it returns 'null', so I can't move further with using the 'insertBefore' method on the parent, since according the my code somewhere, the 'ul' parent element doesn't exist! Help with this is appreciated!

Thank you!

<div class="list">
      <p class="description">Things that are purple:</p>
      <input type="text" class="description">
      <button class="description">Change list description</button>
      <ul>
        <li>grapes
          <button class="up">up</button>
          <button>remove</button>
        </li>
        <li>amethyst 
          <button class="up">up</button>
          <button>remove</button>
        </li>
        <li>lavender 
          <button class="up">up</button>
          <button>remove</button>
        </li>
        <li>plums 
          <button class="up">up</button>
          <button>remove</button>
        </li>
      </ul>
      <input type="text" class="addItemInput">
      <button class="addItemButton">Add item</button>
    </div>
listUl.addEventListener('click', (event) => {
  if (event.target.tagName == 'BUTTON') {
    let li = event.target.parentNode;
    let ul = li.parentNode;
    // remove list item from list.
    ul.removeChild(li);
  }

  if(event.target.className == 'up'){
    let li = event.target.parentNode;
    let parentUl = li.parentNode;
    let prevElement = li.previousElementSibling;
    parentUl.insertBefore(li, prevElement);
  }
});

1 Answer

Emmanuel C
Emmanuel C
7,624 Points

Hey Rochelle,

I didnt see it in your code but i assumed that the variable listUl was equal to the only <ul> in your html.

When they click the up button both if statements are actually running, since the target.tagName is a button and it has the class of "up", So in the first if, the li is being removed from the ul with removeChild. Then when it gets to the second if and tries to call the parentNode of that same li, it returns null since it was removed as a child.

One way of dealing with this is giving a class to the remove button then you can check if the target.className is "remove" which is what i can only assume is suppose to remove the li.

Hope this helps. Good luck!

Rochelle Burrows
Rochelle Burrows
8,232 Points

Emmanuel - thank you so much for such a swift and perfectly explained response. It worked!

Extremely grateful!