Checking if an element exists with jQuery

C

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.

Extending jQuery with an Exists function

Let’s get right to the code:

[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
}
[/code]

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:

[code]
// Call the exists function
if ($(“#myId”).length) {
// Do something because it exists
}
[/code]

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.

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!

About the author

By Jamie

My Books