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

Why use parentNode on li

Online 12 and 13, Guil used javascript let li = event.tagret.parentNode and on 13 he used javascript let ul = li.parentNode I understand the javascript let ul = li.parentNode is asking for its parent but i do not understand why use javascript let li = event.tagret.parentNode when we already have reference to the parentNode is line 13

3 Answers

Joachim Larsen
Joachim Larsen
9,279 Points

The "let li = event.tagret.parentNode" assigns the parent of the event's target, probably an anchor or button element within the list item, to a variable called "li". In other words, this identifies the li element that is the parent of the clicked element (if this is within a click handler).

ywang04
ywang04
6,733 Points

You didn't notice that if conditional statement in this case:

listUl.addEventListener('click',(event)=>{
  if (event.target.tagName ==="BUTTON") {
    let li = event.target.parentNode;
    let ul = li.parentNode;
    ul.removeChild(li);
  }
});

if (event.target.tagName ==="BUTTON") means the event.target is only to target the button element. Actually, you need to find out li element instead of button element while button's parent element is li.

Omar Carmona
Omar Carmona
3,902 Points

If you look in the html file you will see that what you are clicking on isn't necessarily the line itself but the button that is nested within the li element so when you do event.target it's actually referencing the 'up' or 'down' buttons with that class name, depending on which one you clicked on. That is why we use event.target.parentNode to reference the parent node of the button element which is the line element.