I am writing a plugin that is given a id.  it adds some code to that id and starts some events.  the problem I have found is if the container is later overwriten I can't find a way to shut down the events so they don't keep running.  Below is a demo script to show what I have tried.  I can't seem to find anyway to detect test2 doesn't exist and clear the interval.
$(function() {
    
  /* *********************************
  *  Simple example of something that could be done
  *  being told to work on id test2
  ********************************* */
    
  var a=0;
  $("#test2").append('<br>I Ran');
  var id=setInterval(function() {
    console.log("running");  //ctrl+shift+j will see message every second
  },1000);
     
  //try to remove id test2 is removed
  $(document).on("DOMNodeRemoved", function (e) {
    console.log(e.target.id,e.target);
    if (e.target.id=="test2") { //is never true since test2 was added by jquery
  clearInterval(id); //stops message from being writen
    }
  })
     
     
  /* *********************************
  *  Some other part of app that wipes away the above script is playing with
  ********************************* */
     
$(document).on('click','#del',function(){
  $("#test").html('wipe out'); //replaces content of div test with test2.html    
  });
    
});
   <!DOCTYPE html>
<html lang="en">
  <header> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  </header>
  <body>
  <div id="test">
  <div id="2" class="test">
    <div id="test2">help</div>
  </div>
  </div>
  <div id="del">Press here to remove</div>
  </body>
</html> 
     
    