1

I've been working on some memory leaks in Javascript for some time now. I've come to a point where I feel the only solution for at least some of the leaks is to remove a given div and then ALL of it's descendants. Meaning children, grandchildren, etc.

Now I'm under the impression I need a recursive function if I want to do this, but I'm still somewhat new to Javascript. I don't even know if recursion works the same way in Javascript as I'm used to.

I'm open to any ideas on how to do such a thing, perhaps I'm way off the mark with the idea of recursion.

user535617
  • 634
  • 2
  • 7
  • 22
  • Recursion works the same - just be careful to use local variables declared with `var` instead of globals. (And remember that variables have function scope instead of the usual block scope) – hugomg Feb 09 '11 at 20:47
  • Possible duplicate, of http://stackoverflow.com/questions/683366/remove-all-the-children-dom-elements-in-div and if not that question has useful answers. – Loktar Feb 09 '11 at 20:51
  • Are you using any frameworks in your project? I know jQuery has an `empty()` method that removes all children from an element. I'd be surprised if there wasn't an equivalent in Prototype / MooTools / etc. – g.d.d.c Feb 09 '11 at 20:56

3 Answers3

2

This will quickly destroy the node and all its children:

var _dummyNode;
var destroy = function(node){
   if(!_dummyNode) _dummyNode = document.createElement('div');
   _dummyNode.appendChild(node.parentNode.removeChild(node));
   _dummyNode.innerHTML = "";
}
destroy(nodeToDestroy);

It creates a dummy DIV that never gets appended to the doc so doesn't show. The node is removed from its parent and appended to the dummy. It's then wiped out with innerHTML.

However - this will fail if you still have variable references to the nodes. You should use a good Ajax library and only use the appropriate addEventListener to attach events. You shouldn't do:

<div onclick="myFunction();">click me</div>

Because it's not a good separation of concerns, it's hard to maintain, it doesn't properly pass events, and you can only attach one method. And if you do it that way you essentially need to do your own garbage collecting.

mwilcox
  • 4,065
  • 23
  • 20
1

I don't know if I fully understand your desired end result, but setting the innerHTML of the div to a blank screen effectively gets rid of all the child nodes:

document.getElementById('test').innerHTML = '';
Ben Jakuben
  • 3,147
  • 11
  • 62
  • 104
0

You could do something like:

function removeChildren(elem){
    for(var i in elem.children){
        removeChildren(elem.children[i])
        elem.removeChild(elem.children[i])
    }
}
OR
function removeChildren(elem){
    while (elem.hasChildNodes()) {
        removeChildren(elem.lastChild)
        elem.removeChild(elem.lastChild);
    }
}

The latter option is probably better.

invisible bob
  • 864
  • 1
  • 9
  • 24