removeChild 在第二次尝试时不工作

removeChild not working at second attempt

所以我正在为 The Odin Project 做蚀刻素描。所以我有一个容器 div(500 像素 x 500 像素)。在浏览器启动时,我将在 for 循环中使用 javascript appendChid 按 16x16 框填充它。现在,如果用户想要更改框的数量,那么我将在 for 循环中删除 Child,然后在 for 循环中执行另一个 appendChild。

问题是 removeChild 仅在第一次尝试时有效,第二次尝试时收到错误消息:

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

这是我的代码:

//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();

没关系,我是通过这样做得到的:

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