title: Detect click when elements have already been removed
body: <p>I'm trying to detect whether a click has occurred on a DatePicker control or not, but I can't accurately determine whether or not the event target element is a part of the DatePicker or not.</p>
  
  <p>After a lot of debugging I've realized that the main issue is that pieces of the DatePicker are detached from the document, so they are simply not a child of any element.</p>
  
  <p>Thanks to <a href="https://stackoverflow.com/questions/22406505/jquery-ui-datepicker-next-and-prev-buttons-only-have-one-ancestor-e-target-p/22757708">this other question</a> I learned that the reason is that a chunk of the DatePicker is being removed and replaced when switching months, so the element that I get from <code>event.target</code> is detached (it was part of the removed chunk).</p>
  
  <p>So, what can I do to determine that this click happened within my control? I'm trying to write this agnostically of what kind of content is being used, although a specific fix for DatePickers would be ok.</p>
  
  <p>So far what I've done is check if my elements contain a DatePicker, and whether the event target is detached. If so, I assume that the click happened on the DatePicker. This isn't perfect because there could be another DatePicker on the page. Also, the event target being detached doesn't necessarily have to be related to DatePicker.</p>
  
  <p>Here's an example of what I have so far:</p>
  
  <pre><code>$(document).on("click", function (event) {
     const stuff = $("something");
  
     if (stuff.is($(event.target)))          
        return; // click was on stuff
  
     if ($(event.target).closest(stuff).length)
        return; // click was on descendents of stuff
  
     if (stuff.is(":active, :focus"))
        return; // stuff is active or focused
  
     if (stuff.find(":active, :focus").length)
        return; // a descendent of stuff is active or focused
  
     if (stuff.is(".hasDatepicker") || stuff.find(".hasDatepicker").length) {
        // stuff is or has a date picker
        if (!$(event.target).closest($(document)).length) {
           // event target is detached, and there's a date picker in stuff
           // so have to assume click was on stuff's date picker
           return;
        }
     }
  
     // click was not within stuff's elements
  }
  </code></pre>