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

Victor Gentile
Victor Gentile
4,996 Points

"using parentNode to traverse up the DOM." how can I add a Remove button to each new item thats added when item appears

I understand what was taught... trying to have a remove button that appears with each new item that I add to list.

4 Answers

Steven Parker
Steven Parker
170,315 Points

You're getting ahead of the course.

Just hold on. Adding the buttons will be covered in the Getting All Children of a Node with children video coming up later in this stage of the course.

Victor Gentile
Victor Gentile
4,996 Points

Thanks for your time and consideration. I guess that's not a bad thing... thinking ahead about how to add more functionality into my code....obviously it came just a bit later.

Andrew Federico
Andrew Federico
7,483 Points

I had the same concern. Not sure how they will do it later, but I used createTextNode in conjunction with what we already learned.

addItemButton.addEventListener('click', () => {
  let ul = document.getElementsByTagName('ul')[0];
  let li = document.createElement('li');
  let btn = document.createElement('button');
  let tn = document.createTextNode('Remove');
  li.textContent = addItemInput.value;
  ul.appendChild(li);
  addItemInput.value = '';
  li.appendChild(btn);
  btn.appendChild(tn);
});
Steven Parker
Steven Parker
170,315 Points

An easier way is to assign your text to the textContent property of the element:

btn.textContent = 'Remove';
Andrew Phythian
Andrew Phythian
15,522 Points

This is my working solution.

If you amend the line

li.textContent = addItemInput.value;

to

li.innerHTML = addItemInput.value + "<button>Remove</button>";

you should get a Remove button that removes the element you have added.

I haven't yet advanced to the point in this course where this is covered, I anticipate the solution will be different to mine.

Steven Parker
Steven Parker
170,315 Points

Just be aware that a button element added this way won't actually be functional without additional code.

Andrew Phythian
Andrew Phythian
15,522 Points

The code I posted worked until we added the 'Up' and 'Down' buttons. However, after adding class='remove' to the button

li.innerHTML = addItemInput.value + "<button class='remove'>Remove</button>";

it appears to remove successfully again.

Was that the additional code you meant?

Steven Parker
Steven Parker
170,315 Points

Yes, assuming you already have a delegated handler that's looking for that class.