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

Why do we need parentNode of ul

Just cannot figure out why does Guil needed to select UL as such

  let li = event.target.parentNode;
  let ul = li.parentNode;

whereas UL parentNode is listDiv, why not use use

let li = event.target.parentNode;
let ul = event.target
ul.remove(li)

This is my thinking or am I missing something?

2 Answers

Steven Parker
Steven Parker
173,944 Points

The "event.target" is the child of the list item, not the parent. It's the button that was clicked.

So to get the list itself, which is the parent of the list item, the "parentNode" property of the list item is used.

Steven Parker Still confused, why we need parent of UL? when we want to remove LI in it. so parent of LI is UL which we can got from event.target.parentNode

Steven Parker
Steven Parker
173,944 Points

The parent of the event target is the list item. Maybe this "ancestry" list will help:

  • event.target :point_right: the button
  • event.target.parentNode :point_right: the list item (li)
  • li.parentNode :point_right: the list itself (ul) (also event.target.parentNode.parentNode)
Michael Williams
Michael Williams
Pro Student 8,057 Points

Steven Parker, I don't think this is the right terminology, but is the list item a "parent" of sorts to the button, then — hence the parentNode property? Or is it something else since the button is within the list item?

Steven Parker
Steven Parker
173,944 Points

You got it right, the list item is the "parent" of the button. Any "child" element will be contained inside it's "parent" element.

Debra Kellington
Debra Kellington
2,978 Points

Thank you. This conversation helped me to understand it better. I, too, was confused as to the need for the parentNode of the button. The list item is actually the parent.