There seems to be an issue in the code snippet below. The function create()
works fine the first time, but encounters a problem on the second run at the line boxWrapper.appendChild(box);
. It appears that the removeChild
method is causing some disruption in 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();
}
The objective is to clear the contents of box-wrapper and have the ability to append multiple child elements repeatedly.