views:

165

answers:

3

Let's say I have two elements on a page. One is a div, and the other is its child, an achor. Let's say that I've added an event to that anchor via anchor.addEvent('click', ...). If I set the div's .innerHTML = '', does the 'click' event associated with the anchor get removed/disposed of/garbage collected?

+1  A: 

It depends if you have still reference to "anchor" DOM instance. If so, it will stay in memory until all references are removed.

Test example:

var parent = new Element('div');
var child = new Element('div', {
    events : {
        click : function() { 
            alert('child clicked'); 
        }
    }
});
child.innerHTML = 'child content';
parent.appendChild(child);
document.body.appendChild(parent);
parent.innerHTML = 'parent content';
document.body.appendChild(child);
nemisj
A: 
  1. IMHO, you should use empty() instead of innerHTML = "".
  2. The reference will remain like @nemisj said, but it will be "floating" and useless. I did some tests here: test case, maybe you'll find interesting.
Nir
+1  A: 

According to the MooTools API: destroy() is a method that:

Empties an Element of all its children, removes and garbages the Element. Useful to clear memory before the pageUnload.

I suspect that what happens to anchors removed when their parent elements are removed using innerHTML = '' is going to depend on the browser.

jQuery offers an empty() method, I am guessing other libraries probably offer methods too. You can see a pretty good discussion of this topic in Removing an element from DOM.

artlung
I use destroy() in MooTools when I want to completely get rid of something.
Shawn Steward