I was looking for a quick way to check if a existing jQuery selection object remained attached to DOM. I had this need because while working with jQuery UI’s datepicker widget, I noticed that when you click the ‘next’/’prev’ button on the calendar, they are actually removed from DOM and new ones are created. This caused a problem for me because in a project I was working on, where the datepicker is displayed inline in a custom popup dialog, I had a click event bound to the page’s body which closed the popup that contained the datepicker if the click was outside the popup’s boundary. Because the datepicker emitted the click event on a DOM element (<a>) that was no longer attached to DOM, I was closing my popup prematurely.
$.contains(document.documentElement, $this); // true|false
The $.contains() expects as input the Parent DOM element (I’m using the DocumentElement which is the entire HTML document) and the Node that should be checked (not a jQuery selection object – notice I gave it as input $this). Assuming $this was defined as a jQuery selection object (ex. ($this = $(“div.mycontainer”)), the above would report if that selection is still in the DOM tree or not.
Here is an example:
// Tested with jQuery 1.10.2 var $this = $( $.parseHTML("<div/>") ).appendTo("body"); alert( $.contains(document.documentElement, $this) ); // true $this.remove(); alert( $.contains(document.documentElement, $this) ); // false
I figure I would write a quick post about this so that I don’t forget it for the future. Hope it helps others.