In the code below, create()
works fine the first time but in the second time something goes wrong at boxWrapper.appendChild(box);
. seems like the removeChild messes up the parent box-wrapper properties.
function pixels() {
const value = document.querySelector("#value")
const input = document.querySelector("#pixels")
value.textContent = input.value
input.addEventListener("input", (event) => {
value.textContent = event.target.value
})
return input.value;
}
function create() {
var elements = document.getElementsByClassName('box'); // get all elements
let z = elements.length;
let a = pixels();
let b = a * a;
let c = (1 / a) * 100;
if (z == 0) {
for (i = 1; i < (b + 1); i++) {
var boxWrapper = document.getElementById("box-wrapper");
var box = document.createElement("div");
box.innerHTML = '1';
box.style.backgroundColor = "light green";
var input_percen = c + "%";
box.style.width = input_percen;
box.style.height = input_percen;
box.classList.add("box");
box.addEventListener('mouseover', function onMouseover(event) {
event.target.style.backgroundColor = 'black';
});
boxWrapper.appendChild(box);
}
} else {
reset();
}
}
function reset() {
while (div = document.getElementById("box-wrapper")) {
div.parentNode.removeChild(div);
}
create();
}
I am expecting to clear box-wrapper and being able to appendChilds multiple times.
2
Answers
You’re getting that error because you’re removing the div you’re trying to empty itself:
You’re selecting the
parentNode
from#box-wrapper
and then you remove the#box-wrapper
div from the childs.Instead of removing the
div
itself, try setting theinnerHTML
to empty:You are removing the
div#box-wrapper
from the DOM by doing :To remove all children from this div, you could use
replaceChildren()
: