Search code examples
javascriptfunctionnodes

Trouble with appending childNodes


I'm building a to-do list. Almost everything works; new to-dos gets pushed to top, when "X" button is clicked, the to-do is gone. My problem is that I couldn't get a new todo created with the delete "X" on the right hand side.

My full codes are here: https://codepen.io/paddlepop18/pen/Orevvp?editors=0010

I tried placing the delete function on the global scope but it didn't work, and I thought placing it under "createListItem function" would help because it is the parent of the delete function.

I've tested with a "console.log function" and it works perfectly.

This is just the Delete function codes:

function addListItem() { 
todoInputEl.addEventListener("keypress", function(event) {
    if (event.keyCode === 13) {
        let newListItem = createListItem(todoInputEl.value);
        todoListEl.insertBefore(newListItem, 
        todoListEl.childNodes[0]);
        // let newDeleteXX = createDeleteX(todoItemEls);    
        todoListEl.insertBefore(newDeleteXX, 
        // toDeleteEls.childNodes[0]);

        todoInputEl.value = "";
    }
})    

}
function createDeleteX(todoItemEls) {
    const newDeleteX = document.createElement("button");
    newDeleteX.className= "to__delete";
    newDeleteX.textContent = "X";
    return newDeleteX;
}

I have to comment out all the lines relating to the delete function in the addListItem() function because if I don't, any new input will not be cleared after pressing the Enter Key.


Solution

  • In your code sample, your event listener is looking for events on a SPAN,

    todoBodyEl.addEventListener("click", (event) => {
        if (event.target.tagName === "SPAN") {
          let li = event.target.parentNode;
          let ul = li.parentNode;
          ul.removeChild(li);
        }
      });
    

    but when creating a new element, you're adding a button.

    function createDeleteX(todoItemEls) {
        const newDeleteX = document.createElement("button");
        //...
    }
    

    Changing the button to a span (and uncommenting and invoking) fixes the issue. See updated codepen: https://codepen.io/anon/pen/vvqjQd?editors=0010