Skip to content Skip to sidebar Skip to footer

Nested Divs That Can Be Deleted On Click

I have a div and when user clicks on it 20 nested divs each inside of another should be appended.And when any of these divs is clicked it should disappear, without affecting its ch

Solution 1:

https://jsbin.com/mekumaralo/edit?html,css,js,output

var parentD = document.getElementById("1");
window.onload = function() {
  for (var i = 0; i < 10; i++) {
    var div = document.createElement("div");
    div.textContent = "div " + i;
    parentD.appendChild(div);
    parentD = div;
  }
}


function removeChildDiv(event) {

//if the parent is the body, we know this is the root Div element
//alternatively you could compare the node to the root and 
//store the root as a variable 
    if(event.target.parentNode == document.body) {

//if there is a child add the event listener to that child
//before removing the root div
    if (event.target.firstElementChild) {
      event.target.firstElementChild.addEventListener("click", removeChildDiv);
    }
  }

  // changed to firstElementChild
  // firstChild will pick up text nodes, firstElementChild will not.
  while (event.target.firstElementChild) {
    event.target.parentNode.insertBefore(event.target.firstElementChild, event.target);
  }


  event.target.parentNode.removeChild(event.target);
}


parentD.addEventListener("click", removeChildDiv);

Post a Comment for "Nested Divs That Can Be Deleted On Click"