Error removing Child in List (li) Javascript

Asked

Viewed 65 times

-1

Friends! the code I have is this below, but when I remove all items from the list, that is all <li> with the function, I wanted the message of alert, when the person presses the Clear List button again, but instead an error appears which is the following:

Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'. at HTMLInputElement.removeElement (script.js:26)

const $list = document.querySelector('ul')
const $product = document.querySelector('#product')
const $btn = document.querySelector('#btn')
const $reset = document.querySelector('#reset')
 
$btn.addEventListener('click', adcProduct)
 
function adcProduct() {
    const $item = `<li>${$product.value}</li>`
    $list.innerHTML += $item
    $product.value = ''
    $product.focus()
}
 
$product.addEventListener('keydown', (e) => {
    if (e.keyCode === 13) {
        adcProduct()
    }
})
 
$reset.addEventListener('click', removeElement)
 
function removeElement() {
    // Removes an element from the document
    const $ul = document.getElementById("list");
    $ul.removeChild($ul.children[0])
    if($product = '') {
        alert('A lista está vazia')
    }
}
  • $ul.removeChild($ul.[0]) so test

  • Germano, your solution did not work here. Also did not understand why I was negative, because if I asked is why I did not find the solution anywhere and I have tried everything.

  • http://devfuria.com.br/javascript/dom-remove-child/ at a glance at this link,I believe it will help you

  • You will have to pass which node from the list you want to remove, not the value

  • But there it is! I can remove the nodes/Node, what I can’t get is that after removing the nodes and not having any more to remove, the user presses the remove button again, an Alert message appears, warning that there are no more items to be removed.

1 answer

1


Good morning, based on your comments I understood your problem, I came to this resolution :

if ($ul.children[0]) {
    $ul.removeChild($ul.children[0])
} else {
alert('A lista está vazia');
}

before removing the product from the list, I test if it exists, if it exists will delete it from the list, and if it does not exist displays the alert that you want If you wanted to see running I made an example running on the link below: https://playcode.io/646420/

  • Everything worked out right here with your solution. Thank you very much, I no longer knew what to do hehe

  • I’m glad you were able to help you, you also contributed to getting...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.