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

vinayak sapkal
vinayak sapkal
9,802 Points

difficulty to understand these part of code?

listDiv.addEventListener('mouseover', (event) => {
  if (event.target.tagName == 'LI') {
   let li = event.target;
   let ul = li.parentNode;
   ul.removeChild(li);
  }
});

[MOD - edited code block - srh]

2 Answers

Dale Severude
Dale Severude
Full Stack JavaScript Techdegree Graduate 71,274 Points

This code adds an eventListener to the listDiv element for a mouseover event. This listDiv element is a parent element over various listItem elements and it is defined as the currentTarget.

Any child elements can fire this eventListener if a mouseover event occurs. The element that fires this eventListener is called the target element. If this target element is a listItem, then the listItem is defined as a variable, the parent of the listItem is defined as a variable, and then the listItem is removed from the parent element.

So, in short, this code removes any listItem underneath listDiv which is moused over.

listDiv.addEventListener('mouseover', (event) => { 
   if (event.target.tagName == 'LI') { 
      let li = event.target;
      let ul = li.parentNode; 
      ul.removeChild(li); 
   }
});
Colin Sandlin
Colin Sandlin
4,509 Points

Can someone tell me if I'm interpreting the code correctly and help fill in the blanks?

listDiv.addEventListener('click', (event) => {  // Eventlistener waits for click to run function //
   if (event.target.tagName == 'LI') {  // If the target of the click is an item with <li> (one of the listed items) //
      let li = event.target;  // then it assigns (what?) to the variable 'li'? //
      let ul = li.parentNode;  // defines <ul> as the parent of <li> //
      ul.removeChild(li);  // accesses <ul> and removes the child (which will be an <li>) //
   }
});