Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 children. Nested div structure.When, for example, the 10th(highlighted with red) is clicked it should disappear

I'm sorry to bother you if the question is a trivial one. Thank you.

Code :

 function run(e) {
   var div = document.createElement("div"); 
   div.setAttribute('class', 'Delete'); 
   div.addEventListener("click", run); 
   e.target.appendChild(div);
   this.removeEventListener("click", run); 
   e.stopPropagation()

}
function removeChildDiv(e)  
{
    if(e.target.className === 'Delete')  
    {
        e.target.parentNode.removeChild(e.target);
    } 
     document.getElementById("1").addEventListener("click", run);
}

 document.getElementById("1").addEventListener("click", run); 
 document.getElementById("1").addEventListener("click", removeChildDiv);
html, body {
  height: 100%;
  width: 100%;
}

div {
  border: 1px solid black;
  width: 90%;
  height: 90%;
  background-color:green;
}
<div id="1"></div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
202 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...