Search code examples
javascriptdomdom-manipulation

removeChild not working at second attempt


So I am doing the etch-a-sketch on The Odin Project. So I have a container div (500px by 500px). At the start of the browser, I will fill it by 16x16 box using javascript appendChid in for-loop. Now if the user wants to change the number of box, then I will removeChild in for-loop then do another appendChild in for-loop.

Problem is the removeChild only works the first attempt, second attempt it gets error message:

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

Here is my code:

//Create a variable for dimension of sketchpad
let num = 16;
let boxWidth = (500/num) + 'px';
let boxHeight = (500/num) + 'px';

//Create variables for the creation of sketchpad
let sketchPadBox = document.querySelector('#sketchPadBox');
let div = document.createElement('div');

//Create function that adds sketchpad
function createSketch() {
    for (let i = 0; i < num; i++) {
        for (let j = 0; j < num; j++) {
            div = document.createElement('div');
            div.classList.add('box');
            div.style.width = boxWidth;
            div.style.height = boxHeight;
            sketchPadBox.appendChild(div);
        }
    }
}

//Create function that removes existing sketchpad
function removeSketch() {
    for (let i = 0; i < num; i++) {
        for (let j = 0; j < num; j++) {
            sketchPadBox.removeChild(div);
        }
    }
}

//Creates button for resizing the sketchpad
createSketch();
removeSketch();


Solution

  • nevermind, I got it by doing this instead:

    function removeSketch() {
        while (sketchPadBox.firstChild) {
                sketchPadBox.removeChild(sketchPadBox.firstChild);
        }
    }