2

If I have a DOM element which is dynamically added to the page, and then removed using jQuery's $("#id").remove(), is it possible to setup a callback, so when the element is removed, I can execute a custom action.

I was thinking of monkey-patching jQuery's remove() method, so I can check the element's ID and if it matches the one I want, execute the callback, but I'm not sure how.

Are there any better ways to do it? And how can I do it using monkey-patching?

(I'm writing a greasemonkey script, and I can't change the underlying implementation)

Kristina
  • 15,859
  • 29
  • 111
  • 181

1 Answers1

3

You can listen to DOMNodeRemoved event and then filter by your required element.

$( "body" ).bind("DOMNodeRemoved", function(e){

  if(e.target.id == "id") {
     // do something
  }
});

As usual, there is a IE only caveat, so check out this post: http://www.bennadel.com/blog/1623-Ask-Ben-Detecting-When-DOM-Elements-Have-Been-Removed-With-jQuery.htm

Mrchief
  • 75,126
  • 20
  • 142
  • 189
  • 3
    `DOMNodeRemoved`: *"**Deprecated** This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time... Use [Mutation Observers](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) instead if possible."* - Source: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events – Pang May 26 '16 at 02:17
  • @Pang: Care to enhance the answer by sending an example? – Mrchief May 26 '16 at 14:49