skip to Main Content

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


  1. 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();
    }
    
    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search