jQuery: checking whether elements exist

Checking whether elements exist on a given document is a common feature requested by many developers. In fact, some jQuery and JavaScript actions often can actually take place only when a given element (or a set of elements) is present on a given page. Unfortunately, there are some problems with some DOM Core methods.

For example, getElementById() returns null when an element is not present, whereas getElementsByTagName() returns nothing in that case. So the following code works as expected:

var elem = document.getElementById('test');
if(elem !== null) {
    // do something
}

but this one returns nothing:

var elems = document.getElementsByTagName('div');
if(elems) {
  // do something
}

With jQuery, we can easily overcome this problem by using the size() method of the wrapped set, like so:

if($('div').size()) {
  // do something
}

This method returns the number of elements ( a DOM NodeList) contained in the specified jQuery context. For a better performance, you can also use the length property. Note, however, that this property is also available for common DOM NodeLists, so that our previous example can actually be rewritten as:

var elems = document.getElementsByTagName('div');
if(elems.length > 0) {
  // do something
}

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.