If a DOM Element is removed, are its listeners also removed from memory?

后端 未结 6 1767
北荒
北荒 2020-11-22 06:18

If a DOM Element is removed, are its listeners removed from memory too?

6条回答
  •  情书的邮戳
    2020-11-22 06:57

    regarding jQuery:

    the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

    Reference: http://api.jquery.com/remove/

    jQuery v1.8.2 .remove() source code:

    remove: function( selector, keepData ) {
        var elem,
            i = 0;
    
        for ( ; (elem = this[i]) != null; i++ ) {
            if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
                if ( !keepData && elem.nodeType === 1 ) {
                    jQuery.cleanData( elem.getElementsByTagName("*") );
                    jQuery.cleanData( [ elem ] );
                }
    
                if ( elem.parentNode ) {
                    elem.parentNode.removeChild( elem );
                }
            }
        }
    
        return this;
    }
    

    apparently jQuery uses node.removeChild()

    According to this : https://developer.mozilla.org/en-US/docs/DOM/Node.removeChild ,

    The removed child node still exists in memory, but is no longer part of the DOM. You may reuse the removed node later in your code, via the oldChild object reference.

    ie event listeners might get removed, but node still exists in memory.

提交回复
热议问题