Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) 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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Dale Severude
Full Stack JavaScript Techdegree Graduate 71,350 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,512 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>) //
   }
});