squarebrackets
squarebrackets

Reputation: 997

jQuery: Manually delete element after detach()?

I am wondering whether it is necessary to manually delete an element that has been detached with jQuery's detach() function (and all references to it has been null'ed).

Here is the JavaScript that I have tried.

For example:

elem = $(".test").detach();
elem = null;

Is the element completely gone, like with $(".test").remove(); or is something like elem.remove() needed?

Edit: Including my comment to the question:

I am detaching multiple elements. Some of them get reused (reinjected in DOM), but others need to be removed permanently after detaching.

Upvotes: 1

Views: 870

Answers (3)

Bergi
Bergi

Reputation: 665111

Is it necessary to manually delete an element that has been detached with jQuery's detach() function (and all references to it has been null'ed).

You cannot "delete" an element. Garbage collector will automatically collect it when there are no references left. If you have detached it, it will be wiped from the memory without problems.

However, this is not the difference between detach and remove. When simply detaching it, some data that jQuery stored not on the element but in its internal cache will be leaked. You would need to explicitly call the [internal!] cleanData method on the elements to fix that - but you should simply call .remove().

Upvotes: 1

Hanlet Escaño
Hanlet Escaño

Reputation: 17380

Straight from jQuery documentation:

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

and .remove()

method takes elements out of the DOM.

So you should be covered.

Upvotes: 0

rossipedia
rossipedia

Reputation: 59397

You shouldn't have to worry about that. If there isn't a reference around to the element that has been detached, the Garbage Collector will clean it up.

Although, you're probably better off calling remove(). detach() is meant specifically for elements that you want to keep around (it maintains all the jQuery specific data associated with the element). Both end up calling elem.parent.removeChild on the actual DOM element. As far as I know there isn't a way to manually delete or destroy it, but that's the job of the Garbage Collector anyways.

Upvotes: 1

Related Questions