Check an Elements Existence in jQuery

jQuery is probably one of the greatest JavaScript libraries out there (at least for me) and it can do pretty much anything you want. There’s one thing that I often do in my web applications that always makes me think twice while writing it in jQuery: element existence.

You’d think it was fairly straightforward, just do the following:

if ($("#elemn")){
  // code
}

This however doesn’t work because jQuery’s selectors always return an object. Because of this, the if statement will always evaluate as True and your code will always run.

There are many ways to get around this and to check whether or not something exists. Here are a few of my favourites:

This one is my favourite. If jQuery returns an empty object the length property will be zero (empty objects don’t have lengths) and your if statement will evaluate as False.

if ($("#elemn").length){
  // code
}

This is pretty much the same as above but you’re being a little more verbose. Doing it this way is a little more readable in my opinion, but you have to write more.

if ($("#elemn").length > 0){
  // code
}

jQuery .size() also returns 0 on empty objects so this works exactly the same as the previous two.

if ($("#elemn").size()){
  // code
}

As you can see there are a number of excellent ways to check whether or not an element exists using jQuery, and it’s really up to you on which one you use.