开发者

Javascript remove all descendants of a div/node

开发者 https://www.devze.com 2023-02-10 02:29 出处:网络
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 solut开发者_JS百科ion for at least some of the leaks is to remove a given div and th

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 solut开发者_JS百科ion 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.


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.


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 = '';


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消