Question

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.

Was it helpful?

Solution

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top