.removeChild problem

Hello I’m trying to remove child element and I get this error:
Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.

This is my code:

JS

var list = document.getElementById("taskList"); // parent element (ul)
var listItems = document.getElementsByTagName("LI");
  for (var i = 0, total = listItems.length; i < total; i++) {
    listItems[i].addEventListener("click", function () {
      list.removeChild(listItems[i]);
    }, false);
  }

HTML:

<ul id="taskList">
  <li>Test #1<button class="btn-delete"></button></li>
  <li>Test #1<button class="btn-delete"></button></li>
  <li>Test #1<button class="btn-delete"></button></li>
</ul>

First of all, what are you trying to achieve? Do you want the list item to be deleted after its button child is clicked?

Yes. I just noticed that I’m adding event to li element but when I change it to button I have still same problem.

Do you want this event to happen inside li elements inside var list? If so, You should replace the second line with

var listItems = list.getElementsByTagName("li");

This will ensure you’re only selecting list items inside that #taskList element.

As you already mentioned, you want the click event to be listened by the button inside each list item, therefore you’ll need to store the button elements somewhere:

var deleteLiBtn = list.getElementsByTagName('button');

You also need to change the for loop to attach the events to the button elements.

You are sending listItem[i] as part of the argument, that won’t be attached to the event. Your best bet is to work with the this keyword.

With these suggested changes, I end up with this:

var list = document.getElementById("taskList"); // parent element (ul)
var listItems = list.getElementsByTagName("li");
var deleteLiBtn = list.getElementsByTagName("button");
  for (var i = 0; i < deleteLiBtn.length; i++) {
    deleteLiBtn[i].addEventListener("click", function () {
      list.removeChild(this.parentNode);
    }, false);
  }

Does that do what you’re trying to achieve?

3 Likes

Yes, thank you very much!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.