Let’s say I have an element:
Then, after the DOM loads, I bind an event to the element, like so:
Later on, the element gets deleted:
What happens to the bound event? Is it deleted too? Does it linger around? Is it a good practice to clean it up?
According to the jQuery documentation for the
.html() method, the event handlers are removed.
This is done to prevent memory leaks.
.html()is used to set an element’s content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
all bound events and jQuery data associated with the elements are removed.
If you want to retain the data and event listeners, use the
.detach() method instead. The
.detach() method is essentially the same as the
.remove() method except for the fact that it keeps all jQuery data associated with the removed elements (which means that you can append the same element after detaching it, and the events would still be bound).