I've looked through the jQuery Documentation for the answer to this simple question:
Does
replaceWith()
callremove()
ordetach()
under the hood?
I've had no luck with the official documentation; it is ambiguously defined as removing the node. But tests show a memory leak.
The removeEventListener() method removes an event handler from an element.
Removing the event listener first always results in lower memory usage (no leaks). Results: IE6 - memory leak.
Looking at the source code of jQuery (2.1.1), you're asking two different questions.
Does jQuery's replaceWith()
remove event handlers?
Yes. jQuery calls cleanData()
, which is an internal method which removes all data on an element. Since jQuery event handlers are stored in the elements data, they will also get cleaned up.
cleanData()
also removes the event handler attached to the element which triggers the execution of all event handlers stored in the elements data, by calling jQuery.removeEvent()
(another internal method).
Does replaceWith()
call remove()
or detach()
under the hood?
The only time it calls remove()
is if no arguments were provided to replaceWith()
; jQuery treats it as if you were calling remove()
instead of replaceWith()
;
TL;DR: jQuery will clean everything up for you, so there shouldn't be a risk of memory leaks.
FYW if you don't want that behavior take a look a this poorly discussed thread over jQuery tickets http://bugs.jquery.com/ticket/13400
and for those who wont ready expect code, here's an implementation of the replaceWith
that uses detach
instead of remove
with remove()
old.replaceWith( new );
with detach()
old.before( new ).detach();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With