Question

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>
Was it helpful?

Solution

I don't think your cleanGrid function will work quite the way you've coded it. x.childNodes will continue to be truthy even if it's empty (an empty NodeList isn't falsey). So I suspect it's throwing an exception (on the removeChild call) or endlessly looping, which (either way) is why other code isn't running. Try running it in a debugging environment (Firefox+Firebug, IE + Visual Studio or the dev toolkit, whatever) where you can see what's going on.

Here's an off-the-cuff reworking of cleanGrid:

function cleanGrid() {
  var x = document.getElementById("grid");
  while (x.lastChild) {
    x.removeChild(x.lastChild);
  }
}

Or, of course:

function cleanGrid() {
  document.getElementById("grid").innerHTML = "";
}

...since innerHTML, though not standard, is supported by all of the major browsers and most of the minor ones.

OTHER TIPS

T.J. Crowder nailed it down with the logic behind the behavior

However, this will work:

function cleanGrid() {
 var x = document.getElementById("grid");
 var len =x.childNodes.length;
 while(len) {
  x.removeChild(x.lastChild);
 --len;
 }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top