Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

297
Visualizações
Button to delete a grid of squares only works once - Node.removeChild: The node to be removed is not a child of this node

I am doing an etch-a-sketch project and so far it has gone well. I wanted to challenge myself by making a button to "destroy" the new grid that I create with another button.

The problem is the button only works once, then throws the error: Node.removeChild: The node to be removed is not a child of this node**

I solved this after trial and error, by moving my const variable out of the global scope and inside the destroyBtn function. The problem is I don't know why it works. If it's in the global scope, shouldn't querySelectorAll('.grid') always be accessible / targetting a newly created grid?? Thanks for your time.

This works:


const containerBtn = document.querySelector('.container')
const destroyBtn = document.querySelector('#destroybtn')

destroyBtn.addEventListener('click', () => {
    const targetSquares = document.querySelectorAll('.grid') // moved inside function
    for (let i = 0; i < targetSquares.length; i++) {
        containerBtn.removeChild(targetSquares[i])
        
    }
})

This does not:


const containerBtn = document.querySelector('.container')
const destroyBtn = document.querySelector('#destroybtn')
const targetSquares = document.querySelectorAll('.grid') // in global scope

destroyBtn.addEventListener('click', () => {
    for (let i = 0; i < targetSquares.length; i++) {
        containerBtn.removeChild(targetSquares[i])
        
    }
})
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda