views:

28

answers:

1

I have something like this:
//html

<div class="panel">
    <div class="tools">
        <a href="#action1">Action 1</a>
        <a href="#action1">Action 1</a>
        <a href="#action1">Action 1</a>
    </div>
    <div class="list">
        <table>...</table>
    </div>
</div>

//JavaScript (jQuery)

var lookup = $('.panel'),
    buttons = lookup.find('.tools').detach().find('a');
...
//append buttons somewhere

So, here i have '.tools' detached from '.panel' and then i took buttons and append them somewhere else. But what about '.tools' node? Does it beeing garbage-collected or not? Do I have to save detached '.tools', take buttons from it and than destroy it?

If its matter - html part is received via AJAX request and all this code is inside success handler.

+1  A: 

In this case, the buttons variable creates a reference to a child of the detached element, and will prevent the element from getting garbage collected, at least until buttons goes out of scope.

EDIT:

In order for something to be garbage collected, it needs to be detached from the DOM, and there must be no JavaScript variables referencing the element (or any elements within the detached node tree)

For example:

<div id="a">
  <div id="b">
    <div id="c">
        <div id="d"></div>
    </div>
  </div>
</div>

If you want to detach "#b" and have it garbage collected, you can't have any variables pointing to elements b, c, or d.

This would not work:

var c = $('#c')

$('#b).detach()

var c would keep a reference to element #c which is part of #b, so be can not be garbage collected.

This does not work either, because detach returns a reference to the element you are detaching.

var b = $('#b').detach()
mikerobi
So... If I write this: `buttons = lookup.find('.tools').detach().find('a').detach();` Then I'll broke that reference and '.panel' will be garbage collected?
NilColor
@NilColor, No. Your change detaches the 'a' element from .tools, but buttons still maintains a reference to .tools. Panels will not get GC'd because it is referenced by the lookup variable, and because you do not remove it from the DOM.
mikerobi
`buttons = lookup.find('.tools').detach().find('a').detach();` doesn't create reference to '.tools' element, isn't it? Finally `buttons` points to an array of `a` elements detached from '.tools' which is detached from `lookup`. No? And because all of them are detached - there is no problem with DOM hierarchy you mention in the answer.
NilColor