1 - I am adding Div container using JS but once their Counter crosses '5' i want to delete these Div containers ONE BY ONE from [0] index.
2 - Here below is what i have done so far.in which i am even getting the childNodes's Number but i am not able to delete these nodes..
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>
I first decremented your counter to update for both negative and positive values. I then set a flag to detect if your code was decrementing or not. When counter reached 5, decrement is set to true
, where when counter is moving towards 5, decrement is set to false
.
Then your div's were added to an array, where we use a for loop
to traverse through the array, removing a div one by one, until we reach 0, where decrement is set back to 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>