Webistrate - Draw Your Own Conclusions

jQuery: Checking if an element exists

Posted by Jamie Munro | January 2, 2012 | Tags:

Share

You want to do some conditional processing depending on if an item or items exist in your DOM (Document Object Model).

By default, jQuery doesn’t have a function that performs this; however, there is a very simple way to extend jQuery to do so.

Let’s get right to the code:

// Extend jQuery with an "exists" function
jQuery.fn.exists = function() {
return this.length;
};

// Call the exists function
if ($("#myId").exists()) {
// Do something because it exists
}

Some people might consider it overkill to extend jQuery to perform such a simple statement, but sometimes readability is just as important.  This same code could be altered as follows and would accomplish the same thing:

// Call the exists function
if ($("#myId").length) {
// Do something because it exists
}

To perform subsequent checks on other objects, it is basically the same amount of typing; however, by calling an exists function, my code is more readable without the need to add a comment because it’s quite clear what is being done via a descriptive function name.

Summary

jQuery is extremely simple to extend and create custom functions that can then be applied to any jQuery selector – in this case checking if an item exists!

Share


Related Posts

Leave a Reply

You must be logged in to post a comment.

Buy one of my books