I am dynamically adding div to the DOM via JS and using appendChild and later on removeChild. But when appending for the 2nd time it wont work

38 views Asked by At

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.

3

There are 3 answers

0
Douwe de Haan On

You're getting that error because you're removing the div you're trying to empty itself:

function reset() {
    while (div = document.getElementById("box-wrapper")) {
        div.parentNode.removeChild(div);

    }
    create();
}

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 the innerHTML to empty:

function reset() {
    div = document.getElementById("box-wrapper");
    div.innerHTML = '';
    
    create();
}
0
Tom On

You are removing the div#box-wrapper from the DOM by doing :

div.parentNode.removeChild(div);

To remove all children from this div, you could use replaceChildren() :

document.getElementById("box-wrapper").replaceChildren();
0
Eduardo Vianna On

thank you very much. i have gone with:

`function reset() {

var elements = document.getElementsByClassName('box'); // get all elements
console.log(elements.length);
let q = elements.length;
 for(let i = 0; i < q; i++){
 elements[0].remove();
 }`  

Thanks!!