How to Check if jQuery Selection is Attached to DOM

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.

A quick search found this jQuery forum post an the solution entered by users ‘n3ds4‘ and ‘ajpiano‘, which work great. I prefer the one that utilizes jQuery’s sizzle, which is:

$.contains(document.documentElement, $this[0]); // 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[0]). 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[0]) ); // true

$this.remove();
alert( $.contains(document.documentElement, $this[0]) ); // 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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s