Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

javascript - 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 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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...