嵌套的div可以在点击时删除

时间:2017-02-27 19:08:05

标签: javascript

我有一个div,当用户点击它时,应该追加20个嵌套的div,每个都应该被追加。当点击任何这些div时,它应该消失,而不会影响它的子节点。 Nested div structure.When, for example, the 10th(highlighted with red) is clicked it should disappear

如果这个问题很简单,我很抱歉打扰你。谢谢。

代码:



html, body {
  height: 100%;
  width: 100%;
}

div {
  border: 1px solid black;
  width: 90%;
  height: 90%;
  background-color:green;
}

<div id="1"></div>
&#13;
//Put this code as soon as you want to remove the loading gif

//This gets the node or the element you want to remove
var node = document.getElementById("gif");
//This removes the node from the parent div
document.getElementById("parentDiv").removeChild(node);
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

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