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

Adding event listeners and modifying HTML attributes with JavaScript

Hi Guys,

I am currently working on the Javascript and the DOM course and having trouble modifying HTML through JavaScript.

I am attempting to move the delete button from the bottom of the list application to generate inside each <li> element. When clicked the button is supposed to remove the <li> and itself from the <ul>. Right now the first attempt works as anticipated, but the second and third make the delete buttons fall out of alignment with the <li>.

Also, when adding a new item to the end of the list, the buttons are not generating.

Just need some pointers how I could do this better! Please help!

Here is my current workbook

Update eventListener Screenshot Issue

1 Answer

Steven Parker
Steven Parker
231,153 Points

I'm not sure what meant about "alignment", I didn't see anything odd visually. But I did notice that no matter which button you used the topmost item was removed. Here's a mod to identify the specific list item the button is in and remove it instead of the top one:

  removeButton[i].addEventListener ('click', e => {
    let ul = document.getElementsByTagName('ul')[0];
    let li = e.target.parentNode;
    ul.removeChild(li);
  });

And the "add item" handler only creates a new list item, it doesn't put any contents into it other than the text. You'll need additional code to create a button.

This helps so much! Thank you!

I am still having the issue with the mouseover event after an li is deleted. The addEventListener is applying styling to the wrong line item.

I'll update the original question with a screenshot.

Steven Parker
Steven Parker
231,153 Points

It's the same basic issue, instead of relying on the item index (which can change as items are deleted), the handler should use the event object to work on the specific element that was the target of the event:

  listItems[i].addEventListener('mouseover', e => {
      e.target.style.backgroundColor = '#f7f7f7';
  });