Wednesday, August 31, 2011

jQuery check if dom element exists

When we use jQuery method $("#idName"), we will always get a jQuery object, even the DOM element may not be really existing on the web page. Sometimes we want to check if the returned object by $("#idName") really is an existing DOM element on the page. The easiest way to do this is to check the length property of the object:

var fakeDom = $("#fake");
if (fakeDom.length == 0) {
console.log('i am not an existing DOM);
}

There is another way to do this though:

var fakeDom = $("#fake");
if (fakeDom[0] === undefined) {
console.log('i am not an existing DOM);
}

Why do they work? When we check jQuery source code (v1.6.2), we find this:

// HANDLE: $("#id")
else {
elem = document.getElementById( match[2] );

// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}

// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}

this.context = document;
this.selector = selector;
return this;
}

As we can see, jQuery gets the DOM element: elem = document.getElementById( match[2] ). And if the DOM element is valid, it will set the length property of jQuery object to 1:

elem = document.getElementById( match[2] );
if ( elem && elem.parentNode ) {
...
this.length = 1;
this[0] = elem;
}
...
return this;

So, if elem is not a valid DOM, this.length will be 0. From the source code, we also find that the valid DOM elem will be assigned to this[0]. Therefore, if the elem is not valid DOM, this[0] should be undefined. So we can also check if this[0] is undefined.  

No comments: