Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,337 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>) //
   }
});