Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node. at HTMLLIElement.<anonymous>

391 views Asked by At
let inputValue = document.querySelector('.input')
let button = document.querySelector('.button')
let items = document.querySelector('#ul')

button.addEventListener('click', function (){
    let li = document.createElement('li')
    let deleteBtn = document.createElement('X')
    deleteBtn.textContent = 'X'
    li.textContent = inputValue.value
    li.appendChild(deleteBtn)
    items.appendChild(li)

    let removeBtn = document.querySelector('#ul')
    removeBtn.addEventListener('click', (e) => {
        let targetBtn = e.target.parentNode
        items.removeChild(targetBtn)
    })

})

Hi everyone, I am just a newbie in programming. I just created a todolist app in Js. In the above code, the remove button that i created works fine but it shows error in the console. Can anyone help me what is actually happening as I tried several approach, none of did work for me. Thank you

1

There are 1 answers

0
Mina On

You don't need to add the event listener on the ul element, you need to add it to the deleteBtn element, and when clicked it should remove the li element.

button.addEventListener('click', function (){
    let li = document.createElement('li')
    let deleteBtn = document.createElement('button')
    deleteBtn.textContent = 'X'
    li.textContent = inputValue.value
    li.appendChild(deleteBtn)
    items.appendChild(li)

    deleteBtn.addEventListener('click', () => {
       li.remove()
    })

})