Search code examples
javascriptjquerydomlistener

Detaching jQuery listeners from a deleted DOM element


Does deleting a DOM element with the id #foo detach all jQuery listeners that reference that id? For example, if I have a listener on $('#foo #bar'), would that also automatically be deleted? (I am using the elem.parentNode.removeChild(elem) method to delete the element.)

If I have to do manual cleanup, does using the jQuery .off() method like $('#foo').off() also detach all listeners which I attached using $('#foo #bar').on('click', myFunction), or does that only detach?


Solution

  • Does deleting a DOM element with the id #foo detach all jquery listeners that reference that id?

    It does if you use jQuery to do it, e.g.:

    $("#foo").remove();
    

    jQuery handles the cleanup for you. From the documentation:

    In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

    (my emphasis)

    And later, after an example removing <div class="hello">:

    If we had any number of nested elements inside <div class="hello">, they would be removed, too. Other jQuery constructs such as data or event handlers are erased as well.

    (my emphasis)