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])
}
})