In this code when I call the cleanGrid() function my goal was to get rid of the div that was class 'circle' and to replace it with a div with class 'square'. For what I'm really using this code for they are not replacable items so replaceChild() would not work. If I comment out the function call to cleanGrid() the code runs fine and the button just adds a div with class 'square' for each click. What I want to actually happen is for cleanGrid() to remove whatever is in the 'grid' div and leave room for whatever should be added after this function is called--but nothing can be added after this function is called and I'm not sure why.
<body>
<div id="grid"><div class="circle">hello</div></div>
<button onclick="addSquare()">add a Square</button>
<script language="JavaScript">
var g = {};
g.myGrid = document.getElementById("grid");
function addSquare() {
// Calling cleanGrid() is giving me problems.
// I want to wipe everything clean first and then add the divs of the 'square' class.
// But instead it just clears the 'grid' div and doesn't allow anything to be added.
cleanGrid(); // WHY NOT?
var newSquare = document.createElement("div");
newSquare.className = "square";
newSquare.innerHTML = "square";
g.myGrid.appendChild(newSquare);
}
function cleanGrid() {
var x = document.getElementById("grid");
while(x.childNodes) {
var o = x.lastChild;
x.removeChild(o);
}
}
</script>
</body>