从parentNode删除childNodes

时间:2018-11-20 21:37:26

标签: javascript html nodes

1-我正在使用JS添加Div容器,但是一旦它们的计数器越过'5',我就想从[0]索引中一个一个删除这些Div容器。

2-以下是我到目前为止所做的事情。在该过程中,我什至获得了childNodes的编号,但是我无法删除这些节点。.

var counter = 0;

function add_div() {
  var mainDiv = document.getElementById("main-div");

  var divi = document.createElement("DIV");
  divi.setAttribute("ID", "div_id");
  divi.style.backgroundColor = "red";
  divi.style.height = "50px";
  divi.style.width = "50px";
  divi.style.margin = "20px";
  mainDiv.appendChild(divi);
  document.body.appendChild(mainDiv);
  document.body.style.backgroundColor = "blue";
  counter += 1;
  document.getElementById("count").innerHTML = counter;

  //read nodes
  var ch = document.getElementById("main-div").childElementCount;
  document.getElementById("demo").innerHTML = "number of childNodes: " + ch;

  //counter check
  if (counter > 5) {
    mainDiv.removeChild(mainDiv.childNodes[0]);
    // mainDiv.parentNode.removeChild(mainDiv);
  }
}
<button onclick="add_div()">ADD DIV</button>
<div id="count"></div>
<div id="demo"></div>
<div id="main-div"></div>

enter image description here

1 个答案:

答案 0 :(得分:0)

我首先递减您的计数器,以更新负值和正值。然后,我设置flag来检测您的代码是否在递减。当计数器达到5时,减量设置为true,而当计数器移至5时,减量设置为false

然后将您的div添加到一个数组中,在这里我们使用for loop遍历该数组,一个一个地删除一个div,直到达到0,然后将减量设置回false;

var counter = 0;

 let decrement = false;
function add_div() {
  if(!decrement){
    var mainDiv = document.getElementById("main-div");

  var divi = document.createElement("DIV");
  divi.setAttribute("ID", "div_id");
  divi.style.backgroundColor = "red";
  divi.style.height = "50px";
  divi.style.width = "50px";
  divi.style.margin = "20px";
  mainDiv.appendChild(divi);
  document.body.appendChild(mainDiv);
  document.body.style.backgroundColor = "blue";
  counter ++;
  document.getElementById("count").innerHTML = counter;


 
  }
  
  //counter check
  if (counter > 5) {
    decrement = true;
  }
  if(counter <= 0){
      decrement = false;
    }
  if(decrement){
    counter--; //decrement counter
    let holder = [];                                     //place div ID's in array
    document.getElementById("count").innerHTML = counter; //update counter
    let div = document.querySelector('#div_id');           //grab div
    holder.push(div);                                        //push to array
    for(let i = 0; i < 5; i++){
     holder[i].parentNode.removeChild(holder[i]) //removes child
    }
   
  }
  
}
<button onclick="add_div()">ADD DIV</button>
<div id="count"></div>
<div id="demo"></div>
<div id="main-div"></div>