Search code examples
javascriptlogicremovechild

RemoveChild does not work despite there is no error


var disP = document.getElementById("display");
var num = 0;
document.getElementById("plus").addEventListener("click",function(){
    num++;
    var newDiv = document.createElement("div");
    var r = Math.round(Math.random() * 255);
    var g = Math.round(Math.random() * 255);
    var b = Math.round(Math.random() * 255);
    newDiv.style.backgroundColor = "rgb("+r+","+g+","+b+")";
    newDiv.id = "newDiv" + num;
    newDiv.style.width = 100 + "px";
    newDiv.style.height = 100 + "px";
    newDiv.style.position= "relative";
    newDiv.style.display = "inline-block";
    disP.appendChild(newDiv);
    

});

disP.addEventListener("click",function(){
    var newDiv = document.createElement("div");
    disP.appendChild(newDiv);
    disP.removeChild(newDiv);
    
});
#ctrl2 #plus {
    background-color:rgb(128,128,128);
    color:white;
}
<div id="preview">
</div>

<div id="ctrl2">
   <button id="plus" value="+" type="button">+</button> <span>|</span>
</div>

<div id=display></div>

Hi, I am trying to create a function where I can delete any of the individual div(box) regardless the order by clicking the div(box). I get no errors but nothing is happening. I would appreciate any tips and help!

P.S We were told in school to use "RemoveChild()" to get this work without relying on other methods but I am open to other options as well.


Solution

  • Give the disP listener an argument for the event, so you can identify the event's target (the clicked square), so you can remove the clicked square:

    var disP = document.getElementById("display");
    var num = 0;
    document.getElementById("plus").addEventListener("click",function(){
        num++;
        var newDiv = document.createElement("div");
        var r = Math.round(Math.random() * 255);
        var g = Math.round(Math.random() * 255);
        var b = Math.round(Math.random() * 255);
        newDiv.style.backgroundColor = "rgb("+r+","+g+","+b+")";
        newDiv.id = "newDiv" + num;
        newDiv.style.width = 100 + "px";
        newDiv.style.height = 100 + "px";
        newDiv.style.position= "relative";
        newDiv.style.display = "inline-block";
        disP.appendChild(newDiv);
    });
    
    disP.addEventListener('click', e => {
      if (e.target !== disP) e.target.remove();
    });
    #ctrl2 #plus {
        background-color:rgb(128,128,128);
        color:white;
    }
    <div id="preview">
    </div>
    
    <div id="ctrl2">
       <button id="plus" value="+" type="button">+</button> <span>|</span>
    </div>
    
    <div id=display></div>

    (.remove() is a bit less verbose than .removeChild and achieves the same thing)