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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…