This code works well but when I start to remove nodes the complete list disappear and I'm left with one node in the innerHTML, instead of removing one by one gradually which is what I want. To leave a few to none behind perhaps gradually instead of straight one for all displayed in the innerHTML, of the div that displays the removal sort of say... I can perfectly do this to work using arrays but I'm curious if there's an way out without using any(arrays)?
HTML code
<button onClick="remov()">remove</button>
<button onClick="addDiv()">Add Div</button>
<div>
<div></div>
<div></div><div></div>
<div></div>
</div>
<div id="tt"></div>
Javascript Code
var stage = document.getElementsByTagName("div")[0];
var tt = document.getElementById("tt");
function remov() {
if (stage.hasChildNodes()) {
stage.removeChild(stage.firstChild);
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML = stage.childNodes[i].nodeName;
}
if (!stage.hasChildNodes()) {
tt.innerHTML = "no nodes";
}
}
}
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML += stage.childNodes[i].nodeName;
}
function addDiv() {
var a = document.createElement("div");
stage.appendChild(a);
if (!stage.hasChildNodes()) {
tt.innerHTML += stage.firstChild.nodeName;
} else {
tt.innerHTML += stage.lastChild.nodeName
}
}
If you want to display all divs during their removal need to change = to += as below
function remov() {
tt.innerHTML=''; //EDIT forgot to add in this line
if (stage.hasChildNodes()) {
stage.removeChild(stage.firstChild);
for (var i = 0; i < stage.childNodes.length; i++) {
tt.innerHTML += stage.childNodes[i].nodeName; //<------- + needed to display all divs
}
if (!stage.hasChildNodes()) {
tt.innerHTML = "no nodes";
}
}
}
EDIT Fiddle added