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

varlevi
varlevi
8,113 Points

Remove Buttons not Working on Added Items

The code Guil provides in this video doesn't explain how to add a working remove button to each added item to the list. I tried adding this function myself, but wasn't able to figure it out. Anyone else got an idea? Here's a workspaces snapshot with the code:

https://w.trhou.se/imlitsytne

3 Answers

Seokhyun Wie
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Seokhyun Wie
Full Stack JavaScript Techdegree Graduate 21,606 Points
// Add a new list item
addItemButton.addEventListener('click', () => {
  let ul = document.getElementsByTagName('ul')[0];
  let li = document.createElement('li');
  // Add a Button (from a later practice)
  let button = document.createElement('button');
  button.innerHTML = 'Remove';
  li.textContent = addItemInput.value;
  ul.appendChild(li);
 // Append a button to the list item that you just created
  li.appendChild(button);
  // Clear the input box
  addItemInput.value = '';
});

Hi varlevi, I also tried to make buttons whenever I create a new list item. And here's my code. Hope you find it helpful. Have a nice day!

Willemijn B
Willemijn B
5,577 Points

Here's how I fixed that:

addItemButton.addEventListener('click', () => {
  if ( addItemInput.value == '' ) {
    alert('Please enter a value');
  } else {
  let ul = document.querySelector('ul');
  let li = document.createElement('li');
  li.innerHTML = addItemInput.value + '<button>Remove</button>';
  ul.appendChild(li);
  addItemInput.value = '';
  }
});

Basically, I switched out textContent for innerHTML so the button is added to the li item. I suppose it works the same way as Brandon Wie's approach, just a little shorter. :)

I ran the code and it works perfectly fine. It removes the items