简体   繁体   中英

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.

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.

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() .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM