jQuery interview question · Most asked
What is the difference between .remove(), .detach() and .empty(), and how do you avoid memory leaks?
Summary
.remove() removes elements and also their jQuery data and event handlers; .detach() removes elements but keeps data and handlers so you can reinsert them; .empty() removes all child nodes (and their data and handlers) but keeps the element.
Longer Answer
Memory leaks in jQuery pages usually come from: removing elements with native DOM methods (or innerHTML = ...), which leaves jQuery's data and handlers in memory; handlers bound on window or document by widgets that are never destroyed; and closures referencing large detached DOM trees. Use jQuery's removal methods for elements managed by jQuery, unbind global handlers on teardown (namespaces help), and check heap snapshots for detached DOM nodes.
Key Points
- remove: elements + data + handlers.
- detach: keeps data and handlers.
- empty: removes children.
- Native removal can leak jQuery data.
Deep dive: Code Clinic: review a jQuery shopping cart script
More most-asked jQuery questions
- How do you make AJAX requests with jQuery?
- What is the difference between .html() and .text(), and why does it matter for security?
- What is event delegation, and why is it useful?
- What is the difference between $(document).ready(), $(fn), DOMContentLoaded and window.onload?
- How do you bind and unbind events in modern jQuery? What happened to bind, live and delegate?
- What is the difference between .attr() and .prop()?
- What is the difference between preventDefault(), stopPropagation() and returning false in a jQuery handler?
- What is jQuery, and is it still relevant today?