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);
}
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);
}