Solution 1 :

Just looking at this, I think you need to add another parentNode. It seems you are only removing the button right now.

Solution 2 :

Just move this one step further up the hierarchy

function removeItem() {
    this.parentNode.parentNode.removeChild(this.parentNode);
}

Solution 3 :

Use remove() so you are not dealing withe child element references

function removeItem() {
  this.parentNode.remove()
  // this.closest('li').remove()
}

or since you have a reference, just delete it

btn.addEventListener('click', function () { li.remove() })

Problem :

I’m making a to-do list application. I want to delete items by clicking a button attached to the list element, but it only deletes the button and not the entire element. Currently, <li> elements in a <ul> by the following:

function newElement() {
    event.preventDefault(); // stop default redirect

    var li = document.createElement("li"); // create an <li> element

    /* make a text node from the input and put it in the <li> */
    var inputValue = document.getElementById("task").value; // retrieve value of text box
    var t = document.createTextNode(inputValue); // create a text node of the box value
    li.appendChild(t); // put the text node in the single <li>

    /* attach a button to the <li> element that deletes it */
    var btn = document.createElement("BUTTON"); // Create a <button> element
    btn.innerHTML = "X"; // Insert text
    btn.className = "button" // add class name for CSS targeting
    btn.addEventListener('click', removeItem); // add event listener for item deletion

    li.appendChild(btn); // Append <button> to <li> 

    li.addEventListener('click', checkToggle); // add event listener for a click to toggle a strikethrough

    appendItem("list", li); //append the li item to the ul
}

and the function called by the button’s listener appears as:

function removeItem() {
    this.parentNode.removeChild(this);
}

I want the button to delete the entire <li> node, but it only deletes the button portion of it.

Comments

Comment posted by Addis

Please include your html file

Comment posted by epascarello

simply

Comment posted by Rylee

If you use jQuery a great, easy way to do this is to use the

Comment posted by user581733

Oops, didn’t see the one above. I’m new to Stack Overflow.

By